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

◇◆丶佛笑我妖孽 提交于 2019-12-04 15:42:33

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/14705794/what-is-the-equivalent-of-mvcs-defaultmodelbinder-in-asp-net-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!