ASP.NET Web API模型驗證以及異常處理方式

 

ASP.NET Web API的模型驗證與ASP.NET MVC同樣,都使用System.ComponentModel.DataAnnotations。

具體來講,好比有:
[Required(ErrorMessage="")]
[Range(0, 999)]
[Bind(Exclude="")]
[DisplayName("")]
[StringLength(1024)]
...

驗證擴展能夠看這裏:http://dataannotationsextensions.org/

在controller中如何驗證模型呢?

一般是經過ModelState.IsValid.ide

 

public HttpResponseMessage Post(Product product)
{
    if(ModelState.IsValid){
        //
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
    else
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
    }
}

 

還能夠經過"面向切面"的方式,自定義一個模型驗證的特性ActionFilterAttibute特性。ui

 

public class ValidateModelAttribute:ActionFilterAttibute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if(actionContext.ModelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

 

而後須要把自定義的過濾器特性註冊到默認的過濾器集合中去。spa

 

public static class WebApiConfig
{
    public static void Register(HttpConfiguraiotn config)
    {
        config.Filters.Add(new ValidateModelAttribute());
    }
}

 

若是不在全局註冊過濾器,咱們還能夠把過濾器特性打到控制器或控制器方法上去。code

 

[ValidateModel]
public HttpResponseMessage Post(Product product)
{

}
相關文章
相關標籤/搜索