【问题标题】:WebApi, Custom model binder and Data annotationsWebApi、自定义模型绑定器和数据注释
【发布时间】:2016-02-11 20:46:20
【问题描述】:

那么,这三者可以结合起来吗?

当我向服务器发送一个不符合模型注释验证的请求时(在这种情况下为空电子邮件),ModelState.IsValid 为真。

型号

public class UpdateModel
{
    [Required]
    public string Email { get; set; }

    public string Name { get; set; }
}

模型绑定器

public class MyModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var data = actionContext.Request.Content.ReadAsStringAsync().Result;
        var model = JsonConvert.DeserializeObject<UpdateModel>(data);
        bindingContext.Model = model;
        return true;
    }
}

ApiController 中的操作

public IHttpActionResult Update(UpdateModel model)
{
    if (!ModelState.IsValid)
    {
        // this never happens :-(
    }
}

相关但对于 MVC 而不是 WebApi:Custom model binding, model state, and data annotations

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-web-api asp.net-web-api2 model-binding


    【解决方案1】:

    通过 DataAnnotation 进行的验证在 Model Binder 中得到处理。如果您使用自己的 ModelBinder,则必须通过 ModelBinder 中的 DataAnnotation 显式调用验证 - 如果您希望通过 DA 自动验证。

    【讨论】:

      猜你喜欢
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多