Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API model binding

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!

like image 826
Andrew Davey Avatar asked Aug 08 '12 10:08

Andrew Davey


People also ask

What is model binding in Web API?

Model Binding is the most powerful mechanism in Web API 2. It enables the response to receive data as per requester choice. i.e. it may be from the URL either form of Query String or Route data OR even from Request Body. It's just the requester has to decorate the action method with [FromUri] and [FromBody] as desired.

How do I bind data in Web API?

Easiest way is to add ModelBinder attribute to the parameter. In following example, I have added ModelBinder attribute to the "data" parameter, so web API can understand how to use custom model binder, while binding the data. Another way is to add ModelBinder attribute to the type.

What is model binding and give an example?

What is Model binding. Controllers and Razor pages work with data that comes from HTTP requests. For example, route data may provide a record key, and posted form fields may provide values for the properties of the model. Writing code to retrieve each of these values and convert them from strings to .

What is model binding in asp net core?

Model binding allows controller actions to work directly with model types (passed in as method arguments), rather than HTTP requests. Mapping between incoming request data and application models is handled by model binders.


1 Answers

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.

like image 131
Troy Alford Avatar answered Oct 13 '22 09:10

Troy Alford