我正在执行自定义WebApi2
模型绑定器,如下所示:
这是成功创建模型。我正在抑制JSON序列化程序错误,因为它们不对应于默认模型绑定程序通常提供的相同错误。
无论是否需要'和模型上的其他属性一样,ModelState为空。
我如何
public bool BindModel(
HttpActionContext actionContext,
System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(PartyModel))
return false;
var json = actionContext.Request.Content.ReadAsStringAsync().Result;
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
// ignore json serializer errors, as they don't
// seem to mimic the webapi2 default validator names/descriptions.
Error = (s, e) => e.ErrorContext.Handled = true
};
var model = JsonConvert.DeserializeObject<PartyModel>(json, settings);
// at this point the model needs to be validated.
bindingContext.Model = model;
return true;
}
答案 0 :(得分:1)
public bool BindModel(
HttpActionContext actionContext,
System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(PartyModel))
return false;
...
// following lines invoke default validation on model
bindingContext.ValidationNode.ValidateAllProperties = true;
bindingContext.ValidationNode.Validate(actionContext);
return true;
}