我在某些模型中使用了一个子模型类(UserInfo),它应该包含一些与用户相关的信息.例如,该子模型可用于各种模型
- public class Model
- {
- int string Value { get; set; }
- public UserInfo User { get; set; }
- }
我已经创建了一个模型绑定器并在WebApiConfig中注册了它
- config.BindParameter(typeof(UserInfo),new UserModelBinder());
解决方法
看看这个问题
What is the equivalent of MVC’s DefaultModelBinder in ASP.net Web API?,了解你的绑定将在何处发生的一些细节.
我怀疑你的模型是在消息体中传递的吗?
如果是,则WebApi将使用格式化程序对类型进行反序列化并处理模型,默认值为XmlMediaTypeFormatter,JsonMediaTypeFormatter或FormUrlEncodedMediaTypeFormatter.
如果您在模型中发布模型,那么根据您请求或接受的内容类型(application / xml,application / 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)
- {
- //
- }
- }