【发布时间】: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