Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of MVC's DefaultModelBinder in ASP.net Web API?

Tags:

I want to create a custom model binder in ASP.Net Web API. There are plenty of resources on how to do this from scratch, but I want to leverage existing functionality.

I have looked around in the source on codeplex and can see plenty of modelbinders in there but most are sealed... and even then I can't work out which one would be used in which situations.

Here is my api method header:

public async Task<HttpResponseMessage> Post(long appId, [FromBody]Field field) 

What I want to do is basically intercept the modelbinder after it has populated all the basic properties, and then set some extra values based on http request headers that I'll be setting on the client side.

As I say, I am comfortable with creating custom modelbinders and modelbinderproviders and wiring them in, the bit I'm having a problem with is trying to re-use the existing functionality provided.

Thanks, Pete

like image 929
beyond-code Avatar asked Feb 05 '13 10:02

beyond-code


People also ask

What is difference between FromQuery and FromBody?

[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data. [FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.

What is FromBody and FromUri in Web API?

The [FromUri] attribute is prefixed to the parameter to specify that the value should be read from the URI of the request, and the [FromBody] attribute is used to specify that the value should be read from the body of the request.


1 Answers

Take a look here for the extension points for WebApi.

There is no exact equivalent for MVC's DefaultModelBinder in WebApi.

If you are using the [FromBody] attribute then the FormatterParameterBinding will be invoked and a MediaTypeFormatter will be used to construct your model.

The model binders for the URI path and Url (Query Params) will invoke ModelBinderParameterBinding which will pass on to either a IValueProvider or a IModelBinder...

So...

In your example Field (depending on the result of content type negotiation) will use one of these: XmlMediaTypeFormatter, JsonMediaTypeFormatter or FormUrlEncodedMediaTypeFormatter. It is therefore up to you to customise the serialisation behavior of these using their respective settings e.g. JSON.NET settings... or implement your own or wrapped MediaTypeFormatter.

In your example the appId will probably be passed on to a IValueProvider... like ElementalValueProvider.

like image 149
Mark Jones Avatar answered Sep 30 '22 20:09

Mark Jones