1

When using ASP.NET Web Api 2 I always need to include the same code:

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

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

I would like to move validation to the base controller that will be executed on each request. But there are many methods to override and I don't know, which one should I use and how.

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

Is there any example for validation in a base class for ASP.NET Web Api?

1 Answer 1

6

Example from 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);
        }
    }
}

and add this attribute to your methods

[ValidateModel]
public HttpResponseMessage SomeMethod1(Model1 model)
1
  • You could also register the action filter to run for all actions without having to use attributes. Might require checking in OnActionExecuting which method was used (as GET and DELETE do not usually receive a model). Commented Nov 22, 2013 at 14:43

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.