Follow @endyourif rss Facebook LinkedIn

Using ActionFilterAttribute to validate all form input Using ActionFilterAttribute to validate all form input

Published on Feb 1, 2020

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:


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)
        {
            
        }
    }
}


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:


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



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:


actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, actionContext.ModelState);


Here is the final results of the snippets:


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

Tags: Entity Framework | actionfilter | modelstate

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP