Frage

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?

War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top