2017-12-04 7 views
0

WebApi2モデルバインダーを次のように実行しています。 これでモデルが正常に作成されています。 JSONシリアライザのエラーは、デフォルトのモデルバインダで通常提供されるエラーと同じではないため、表示されません。webapi2でカスタムモデルバインダーを使用しているときにモデルを検証する

モデルに関係なく、「必須」およびその他の属性は、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; 
    } 

答えて

0
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; 
    } 
関連する問題