2

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.

1
  • I was able to get this to work if I type the parameter ( {pid:int} ) and have the input parameter be an integer rather than an object. Why does it not work as written above? Commented Jul 20, 2015 at 16:02

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.