Web API model binding

Andrew Davey picture Andrew Davey · Aug 8, 2012 · Viewed 7.3k times · Source

Given the ASP.NET Web API route:

example/{Id}

Which maps to the following ApiController action method:

public void Example(Model m)
{
    ...
}

With the model class defined as:

public class Model
{
    public int Id { get; set; }
    public string Name { get; set; }
}

When I post JSON { "Name": "Testing" } to the URL /example/123 then Id property of the Model object is not bound. It remains as 0 instead of 123.

How can I make the model binding also include values from the route data? I'd prefer not having to write custom model binders for what seems like a common use case. Any ideas would be greatly appreciated. Thanks!

Answer

Troy Alford picture Troy Alford · Dec 20, 2012

The easiest way to accomplish what you're looking for is just to add another parameter to your method, and specify which parameter comes from which part of the request.

Example:

[HttpPost]
public void Example([FromUri]int id, [FromBody]Model m) {
    // ...
}

Now your route of /examples/{id} will successfully be able to bind - because the Example method has a parameter called id which it is looking for in the URI. To populate your model, you can either pass the ID in there as well, or do something like the following:

[HttpPost]
public void Example([FromUri]int id, [FromBody]Model m) {
    m.Id = id; // Make sure the model gets the ID as well.
}

Then simply post in { "Name": "Testing" } to /example/123 as you mentioned above.