Asp.net mvc 4 ModelBinder和子模型

Asp.net mvc 4 ModelBinder和子模型,asp.net-mvc-4,asp.net-web-api,model-binding,Asp.net Mvc 4,Asp.net Web Api,Model Binding,我在一些模型中使用了一个子模型类(UserInfo),它应该包含一些与用户相关的信息。例如,此子模型可用于各种模型 public class Model { int string Value { get; set; } public UserInfo User { get; set; } } 我已经创建了一个模型绑定器并在WebApiConfig中注册了它 config.BindParameter(typeof(UserInfo), new UserModelBinder(

我在一些模型中使用了一个子模型类(UserInfo),它应该包含一些与用户相关的信息。例如,此子模型可用于各种模型

public class Model
{
     int string Value { get; set; }
     public UserInfo User { get; set; }
}
我已经创建了一个模型绑定器并在WebApiConfig中注册了它

config.BindParameter(typeof(UserInfo), new UserModelBinder());
问题是WebApi处理管道没有调用UserModelBinder。这些模型绑定器似乎不是为子模型调用的。我错过什么了吗

HttpConfigurationExtensions.BindParameter方法注册 动作上的给定参数类型将使用模型进行绑定 活页夹

因此,您所做的类似于:

void Action([ModelBinder(UserModelBinder)] UserInfo info)
仅当操作参数为指定类型(UserInfo)时,它才起作用

尝试将模型绑定器声明放在UserInfo类本身上,以便它是全局的:

[ModelBinder(UserModelBinder)] public class UserInfo { }

但是,WebAPI和MVC绑定参数的方式存在一些差异。这是Mike Stall的详细说明。

看看这个问题,了解绑定将发生在哪里的一些细节

我怀疑您的
模型
正在消息体中传递

如果是,WebApi将使用格式化程序反序列化类型并处理模型,默认值为
XmlMediaTypeFormatter
JsonMediaTypeFormatter
FormUrlEncodedMediaTypeFormatter

如果要在正文中发布模型,则根据您请求或接受的内容类型is(应用程序/xml、应用程序/json等),您可能需要自定义serialiser设置或包装或实现自己的
MediaTypeFormatter

如果您使用的是application/json,那么您可以使用
JsonConverters
自定义UserInfo类的序列化。这里和这里都有一个例子

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)
    {
        //
    }
}