Web Api:基本控制器验证

时间:2013-11-22 14:01:51

标签: asp.net asp.net-mvc asp.net-web-api

使用ASP.NET Web Api 2时,我总是需要包含相同的代码:

public IHttpActionResult SomeMethod1(Model1 model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    //...
}

public IHttpActionResult SomeMethod2(Model2 model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    //...
}

我想将验证移到将在每个请求上执行的基本控制器。但是有很多方法可以覆盖,我不知道,我应该使用哪种方法以及如何使用。

public class BaseController : ApiController
{
    public void override SomeMethod(...)
    {
        if (!ModelState.IsValid)
        {
            // ???
        }
    }
}

ASP.NET Web Api的基类中是否有任何验证示例?

1 个答案:

答案 0 :(得分:6)

来自asp.net

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

并将此属性添加到您的方法

[ValidateModel]
public HttpResponseMessage SomeMethod1(Model1 model)