我在某些模型中使用了一个子模型类(UserInfo),它应包含一些与用户相关的信息。该子模型可用于各种模型,例如
public class Model
{
int string Value { get; set; }
public UserInfo User { get; set; }
}
我已经创建了一个模型绑定器并在WebApiConfig中注册了它
config.BindParameter(typeof(UserInfo), new UserModelBinder());
问题是WebApi处理管道没有调用UserModelBinder。似乎这些模型绑定器不适用于子模型。我错过了什么吗?
答案 0 :(得分:1)
HttpConfigurationExtensions.BindParameter 方法注册表示 Action上的给定参数类型将使用模型绑定 粘合剂。
所以你所做的就像:
void Action([ModelBinder(UserModelBinder)] UserInfo info)
仅当action参数具有指定类型(UserInfo)时才有效。
尝试在UserInfo类本身上放置模型绑定器声明,以便它是全局的:
[ModelBinder(UserModelBinder)] public class UserInfo { }
但是,WebAPI和MVC绑定参数的方式存在一些差异。这是Mike Stall的详细explanation。
答案 1 :(得分:1)
请查看此问题What is the equivalent of MVC's DefaultModelBinder in ASP.net Web API?,了解有关绑定将在何处发生的详细信息。
我怀疑你的Model
是否正在邮件正文中传递?
如果是,那么WebApi将使用格式化程序对您的类型进行反序列化并处理模型,默认值为XmlMediaTypeFormatter
,JsonMediaTypeFormatter
或FormUrlEncodedMediaTypeFormatter
。
如果您在模型中发布模型,那么根据您请求或接受的内容类型(application / xml,application / json等),您可能需要自定义序列化设置或包装或实现您自己的{{1 }}
如果您正在使用application / json,那么您可以使用MediaTypeFormatter
来自定义UserInfo类的序列化。这里有一个例子Web API ModelBinders - how to bind one property of your object differently和WebApi Json.NET custom date handling
JsonConverters