Web API Action Filters

One of the challenges working with web services is assuming that the consuming applications are going to do the validation that they should. One way to insure validation takes place when using the ASP .NET Web Api is to write a custom Action Filter. Action filters allow you to validate the input before the controller action executes and are also a convenient way to reuse validation code amoung multiple controller actions.

Here is an example. I have a number of action methods to write for an ASP .NET Web API web service and I want to make sure that a maximum input length validation is availble for any method on and of the controllers. Here is one of the action methods that I want to validate. It excepts a search term string and I want to validate the length of the string in a way that can be reused with other controller actions.

  public IHttpActionResult Get(string term)  {           SearchResult results = //..Do Search           return Ok(results);  }  

Now I create a class named MaxInputLengthActionFilter that in inherits from ActionFilterAttribute and overrides the OnActionExecuting and OnActionExecuted methods. In this case I am interested in the OnActionExecuting method because I want to intercept the request before the controller action executes a search. Notice that when the input exceeds the length for a search term, I am adding a “BadRequest” http status code to signfy that the request is invalid. This also halts the execution of the controller action. Along with the “BadRequest” error code that is sent to the consuming application, a custom error message can be added in the ReasonPrase property of the request. This gives the consuming application a descriptive message of the request.

  public class MaxInputLengthActionFilter : ActionFilterAttribute  {          public override void OnActionExecuting(HttpActionContext filterContext)          {              foreach(KeyValuePair args in filterContext.ActionArguments)              {                  if (Convert.ToString(args.Value).Length >          Convert.ToInt32(ConfigurationManager.AppSettings["MaxInputLength"]))                  {                      filterContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);                      filterContext.Response.ReasonPhrase = "Exceeds maximum allowed length for input parameter.";                  }              }          }       //…  }  

The last step that is required is to add the attribute to the controller action that you want to validate. Here is an example of the action method with the MaxInputLengthActionFilter.

  [MaxInputLengthActionFilter]  public IHttpActionResult Get(string term)  {           SearchResult results = //..Do Search           return Ok(results);  }  

Now you can simply add this attribute whenever you create another controller action and need to enforce a max length on the input parameters.