8

I use in some models a sub model class (UserInfo) which should contain some user related info. This sub model can be used in various models, For example

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

I've created a model binder and registered it in WebApiConfig

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

The thing is the UserModelBinder isn't called by the WebApi processing pipeline. It seems that these modelbinders aren't called for the sub models. Am I missing something ?

user49126
  • 1,825
  • 7
  • 30
  • 53

2 Answers2

1

HttpConfigurationExtensions.BindParameter method register that the given parameter type on an Action is to be bound using the model binder.

so what you did is similar to:

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

It works only if action parameter is of specified type (UserInfo).

Try putting model binder declaration on UserInfo class itself, so that it's global:

[ModelBinder(UserModelBinder)] public class UserInfo { }

However, there are some differences in the way how WebAPI and MVC bind parameters. Here is Mike Stall's detailed explanation.

Nenad
  • 24,809
  • 11
  • 75
  • 93
1

Take a look at this question What is the equivalent of MVC's DefaultModelBinder in ASP.net Web API? for some detail on where your bindings are going to be happening.

I suspect though that your Model is being passed in the message body?

If it is then WebApi will use a formatter to deserialise your types and process the model, the defaults being XmlMediaTypeFormatter, JsonMediaTypeFormatter or FormUrlEncodedMediaTypeFormatter.

If you are posting the model in the body then depending on your requested or accepted content-type is (application/xml, application/json etc) you may need to customise the serialiser settings or wrap or implement your own MediaTypeFormatter.

If you are using application/json then you can use JsonConverters to customise the serialisation of your UserInfo class. There is an example of this here Web API ModelBinders - how to bind one property of your object differently and here WebApi Json.NET custom date handling

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)
    {
        //
    }
}
Community
  • 1
  • 1
Mark Jones
  • 12,156
  • 2
  • 50
  • 62