簡體   English   中英

在webapi2中使用自定義模型綁定程序時驗證模型

[英]validating a model when using a custom model binder in webapi2

我正在按如下方式執行自定義WebApi2模型綁定程序:這將成功創建模型。 我抑制了JSON序列化器錯誤,因為它們與默認模型綁定程序通常提供的相同錯誤不對應。

無論模型上是“必需”還是其他屬性,ModelState為空。

我該怎么辦

  • 調用默認模型綁定程序以獲取具有所有相關模型狀態錯誤的PartyModel?
  • 序列化我可以執行的屬性后,執行默認的模型驗證器以用相關的錯誤填充模型狀態。

    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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM