In the WebApi tutorial http://www.asp.net/web-api/overview/web-api-routing-and-actions/creating-a-web-api-that-supports-crud-operations there is an example of a PUT handler. It looks like this:
public void PutContact( int id, Contact contact ) { ... }
And the route URI looks like /api/contacts/{id}
The tutorial suggests that the id parameter will get populated from the URL (e.g. /api/contacts/2 means the id parameter would be 2) and the complex type parameter will get populated from the request body.
However when I test this, I find that the id parameter is populated from the Contact.Id property from the object in the request body and that {id} value from the request URI is seemingly ignored.
Is this a bug? Is there some way to get the {id} value passed in to the handler?
In MVC model binding maps from the form, route and query string values to your parameters. This is also the order it uses, so post values will be used before route parms.
dthein
Member
2 Points
1 Post
PUT handler parameter not getting set from URI
Apr 03, 2012 03:47 PM|LINK
In the WebApi tutorial http://www.asp.net/web-api/overview/web-api-routing-and-actions/creating-a-web-api-that-supports-crud-operations there is an example of a PUT handler. It looks like this:
public void PutContact( int id, Contact contact ) { ... }
And the route URI looks like /api/contacts/{id}
The tutorial suggests that the id parameter will get populated from the URL (e.g. /api/contacts/2 means the id parameter would be 2) and the complex type parameter will get populated from the request body.
However when I test this, I find that the id parameter is populated from the Contact.Id property from the object in the request body and that {id} value from the request URI is seemingly ignored.
Is this a bug? Is there some way to get the {id} value passed in to the handler?
BrockAllen
All-Star
27532 Points
4906 Posts
MVP
Re: PUT handler parameter not getting set from URI
Apr 03, 2012 04:01 PM|LINK
In MVC model binding maps from the form, route and query string values to your parameters. This is also the order it uses, so post values will be used before route parms.
DevelopMentor | http://www.develop.com
thinktecture | http://www.thinktecture.com/
MikeWasson
Member
486 Points
78 Posts
Microsoft
Re: PUT handler parameter not getting set from URI
Apr 03, 2012 04:24 PM|LINK
You're right, if the Contact object in the message body contains an ID, that will be used for the id parameter.
You can force Web API to use the URI by adding the [FromUri] attribute to the parameter: