8

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

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

我创建了一个模型绑定器并在 WebApiConfig 中注册了它

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

问题是 WebApi 处理管道没有调用 UserModelBinder。似乎子模型没有调用这些模型绑定器。我错过了什么吗?

4

2 回答 2

1

HttpConfigurationExtensions.BindParameter方法注册将使用模型绑定器绑定 Action 上的给定参数类型。

所以你所做的类似于:

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

仅当操作参数为指定类型 (UserInfo) 时才有效。

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

[ModelBinder(UserModelBinder)] public class UserInfo { }

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

于 2013-02-04T16:28:01.620 回答
1

看看这个问题ASP.net Web API中MVC的DefaultModelBinder是什么等价物?有关绑定将在何处发生的一些详细信息。

我怀疑您Model是否正在消息正文中传递?

如果是,那么 WebApi 将使用格式化程序来反序列化您的类型并处理模型,默认XmlMediaTypeFormatter值为JsonMediaTypeFormatterFormUrlEncodedMediaTypeFormatter

如果您在正文中发布模型,则根据您请求或接受的内容类型是(应用程序/xml、应用程序/json 等),您可能需要自定义序列化器设置或包装或实现您自己的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)
    {
        //
    }
}
于 2013-02-07T09:31:57.293 回答