Web.API 2 centralised model state validation

Model state validation is easy with DataAnnotations. However, you will find repeating the next line of code very soon:


if(!ModelState.IsValid) return BadRequest(..);

Luckily, there is a pretty simple solution – to use ActionFilter:

using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace MyAwesomeWebApi.ActionFilters
{
/// <summary>
/// Returns 400 if the ModelState is invalid.
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid)
return;
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using System.ComponentModel.DataAnnotations;
namespace MyAwesomeWebApi.Controllers
{
public class ValuesController : ApiController
{
[ValidateModel]
public IHttpActionResult Post(MyModel model)
{
var valService = new ValService();
var result = valService.Create(model);
return Created($"api/values/{result.Id}", result);
}
}
public class MyModel
{
[Required]
public int Id { get; set; }
}
}
view raw ValuesController.cs hosted with ❤ by GitHub

All you have to do is to add the ValidateModel attribute to your controller methods that require model state validation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s