我在一些模型中使用子模型类(UserInfo),它应该包含一些与用户相关的信息。该子模型可用于各种模型,例如
public class Model
{
int string Value { get; set; }
public UserInfo User { get; set; }
}我已经创建了一个模型绑定器,并在WebApiConfig中注册了它
config.BindParameter(typeof(UserInfo), new UserModelBinder());问题是WebApi处理管道不会调用UserModelBinder。似乎这些模型绑定器不是为子模型调用的。我是不是漏掉了什么?
发布于 2013-02-07 17:31:57
有关绑定将在何处发生的一些详细信息,请查看此问题What is the equivalent of MVC's DefaultModelBinder in ASP.net Web API?。
我怀疑您的Model是在消息体中传递的吗?
如果是,那么WebApi将使用格式化程序反序列化您的类型并处理模型,缺省值为XmlMediaTypeFormatter、JsonMediaTypeFormatter或FormUrlEncodedMediaTypeFormatter。
如果您在正文中发布模型,那么根据您请求或接受的内容类型(应用程序/xml、应用程序/json等),您可能需要定制序列化程序设置,或者包装或实现您自己的MediaTypeFormatter。
如果你正在使用application/json,那么你可以使用JsonConverters来定制你的UserInfo类的序列化。这里有一个这样的例子,Web API ModelBinders - how to bind one property of your object differently和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-05 00:28:02
HttpConfigurationExtensions.BindParameter方法注册
上的给定参数类型将使用模型绑定器进行绑定。
因此,您所做的类似于:
void Action([ModelBinder(UserModelBinder)] UserInfo info)仅当操作参数为指定类型(UserInfo)时才起作用。
尝试将模型绑定器声明放在UserInfo类本身上,这样它就是全局的:
[ModelBinder(UserModelBinder)] public class UserInfo { }但是,WebAPI和MVC绑定参数的方式有一些不同。以下是Mike Stall的详细explanation。
https://stackoverflow.com/questions/14689505
复制相似问题