ModelBinder and Utility Models

In some models, I use a submodel class (UserInfo), which should contain some information related to the user. This auxiliary model can be used in various models, for example

public class Model { int string Value { get; set; } public UserInfo User { get; set; } } 

I created a model binding and registered it in WebApiConfig

 config.BindParameter(typeof(UserInfo), new UserModelBinder()); 

The fact is that UserModelBinder is not called by the WebApi processing pipeline. It seems that these model lines are not called for submodel models. Did I miss something?

+8
asp.net-web-api asp.net-mvc-4 model-binding
source share
2 answers

Take a look at this question. What is the equivalent of MVC DefaultModelBinder in the ASP.net web interface? for details of where your bindings will take place.

I suspect your Model is being sent in the body of the message?

If in this case WebApi will use the formatter to deserialize your types and process the model, the default values ​​are XmlMediaTypeFormatter , JsonMediaTypeFormatter or FormUrlEncodedMediaTypeFormatter .

If you send the model to the body, then depending on your requested or accepted type of content (application / xml, application / json, etc.) you may need to configure serializer settings or wrap or implement your own MediaTypeFormatter .

If you are using the / json application, you can use JsonConverters to serialize your UserInfo class. Here is an example of this Web API ModelBinders - how to bind one property of your object in a different way and here WebApi Json.NET personalized data processing

 internal class UserInfoConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeOf(UserInfo); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { // } } 
+1
source share

The HttpConfigurationExtensions.BindParameter method will register that the specified parameter type in Action should be bound using the binder model.

what you did looks like:

 void Action([ModelBinder(UserModelBinder)] UserInfo info) 

It works only if the action parameter is of a specific type (UserInfo).

Try placing the binding object declaration in the UserInfo class so that it is global:

 [ModelBinder(UserModelBinder)] public class UserInfo { } 

However, there are some differences in the way the WebAPI and MVC binding options. Here Mike Stoll explained the explanation in detail.

+1
source share

All Articles