[英]validating a model when using a custom model binder in webapi2
我正在按如下方式執行自定義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;
}
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.