user1613797
user1613797

Reputation: 1267

Web Api: Base controller validation

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?

Upvotes: 1

Views: 1756

Answers (1)

Dmytro Rudenko
Dmytro Rudenko

Reputation: 2524

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)

Upvotes: 6

Related Questions