Separate or combined ServiceStack services?

时光怂恿深爱的人放手 提交于 2019-12-06 10:17:27

问题


I want to have ServiceStack endpoints such as the following...

[RestService("/items/recent")]
[RestService("/items/recent/{Page}")]
[RestService("/items/popular")]
[RestService("/items/popular/{Page}")]

Since both would return a List<Item>, I'd love to be able to have both of these in the same RestServiceBase for easier code management. Is this possible? If so, how can I differentiate the request when it comes in to find whether it was a "recent" or "popular" request so that I can handle it appropriately?


回答1:


Yes you can have multiple REST-ful paths pointing to the same web service.

If you want to leave the paths as-is you can inspect the Request Path used to invoke the service via the HttpRequest, i.e:

var httpReq = base.RequestContext.Get<IHttpRequest>();
httpReq.PathInfo //or httpReq.RawUrl, httpReq.AbsoluteUri, etc.

The way you work out what type of request it is, is by looking at the populated Request DTO - but to distinguish between /recent/ and /popular/ you should store it in another Request DTO property and then inspect its values i.e.

[RestService("/items/{Type}")]
[RestService("/items/{Type}/{Page}")]
public class Items
{
    public string Type { get; set; }
    public int? Page { get; set; }
}

public class ItemsService : ServiceBase<Items>
{
    public override object Run(Items request)
    {
        if (request.Type == "recent")
           if (!request.Page.HasValue) 
              //path 1
           else
              //path 2
        else if (request.Type == "popular")
           if (!request.Page.HasValue) 
              //path 3
           else
              //path 4
    }
}

This is also similar to this StackOverflow question: Need help on servicestack implementation



来源:https://stackoverflow.com/questions/8415972/separate-or-combined-servicestack-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!