Using ActionFilterAttribute to validate all form input

U

I’m a big fan of using ActionFilterAttribute to apply a global filter on every single ASP.NET MVC request. I am going to create a custom filter that will implement ActionFilterAttribute to validate that the ModelState is valid for all POST or PUT requests.

Combining ActionFilterAttribute with ModelState

I’m going to start with a file called ValidationActionFilterAttribute because it is a verbose name that defines exactly what it is doing. Here is a shell of the class that extends the action filter:

[code]
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;

namespace Filters
{
public class ValidationActionFilterAttribute : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{

}
}
}
[/code]

The core of the code will go inside the overridden OnActionExecuting function. Now I’m going to fill in the key if statement that will check if the ModelState is valid:

[code]
if (!actionContext.ModelState.IsValid)
{
// TODO: Provide friendly error message
}

[/code]

If the form is not valid, it will fall inside our if statement. The final piece of this is to provide a useful error message. Inside the actionContext.ModelState I can access the error messages with that variable. The final piece of the puzzle is to define the result with a 400 Bad Request response with the friendly error message:

[code]
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
[/code]

Here is the final results of the snippets:

[code]
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;

namespace Common.Filters
{
public class ValidationActionFilterAttribute : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
}
[/code]

About the author

By Jamie

My Books