Search code examples
c#asp.netattributerouting

ASP.NET Web API Attribute Routing: RoutePrefix with Route Parameter


Is it possible in ASP.NET to have a RoutePrefix attribute on an ApiController that contains a route parameter?

[RoutePrefix("api/parent/{pid}/child")]
public class ChildController : ApiController
{
    [Route("")]
    public HttpResponseMessage Get(object pid)
    {
        //...
    }

    [Route("{cid}"]
    public HttpResponseMessage Get(object pid, object cid)
    {
        //...
    }
}

I would like to have the pid parameter accessible to all controller methods.


Solution

  • You can't use object as the parameter type because Web API doesn't know how to convert a string to an object. You have to use a simple type such as int, string, Guid, etc. If you want to use a complex type, you have to use the FromUri attribute or write a custom converter for it.

    More info on http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api