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
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 theFormatterParameterBinding
will be invoked and aMediaTypeFormatter
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 aIValueProvider
or aIModelBinder
...So...
In your example
Field
(depending on the result of content type negotiation) will use one of these:XmlMediaTypeFormatter
,JsonMediaTypeFormatter
orFormUrlEncodedMediaTypeFormatter
. 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 aIValueProvider
... like ElementalValueProvider.