public class CustomerModel
{
[Required]
public int FirstName { get; set; }
[Required]
public int LastName { get; set; }
}
{
"message": "The request is invalid.",
"modelState": {
"model.FirstName": [
"The FirstName field is required."
],
"model.LastName": [
"The LastName field is required."
]
}
}
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;
using System;
using System.Web.Http.ModelBinding;
using System.Collections.Generic;
namespace MyApp.Web.Infrastructure.Filters
{
/// <summary>
/// This action attribute is used to validate the view model. It will throw 422 - Unprocessable
/// entity in case model (modelState) was not validated.
/// <see href="http://stackoverflow.com/questions/11686690/handle-modelstate-validation-in-asp-net-web-api"/>
/// <seealso href="http://stackoverflow.com/a/3291292/413785"/>
/// </summary>
public class ValidationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
var model = actionContext.ActionArguments["model"];
if (model != null)
{
var modelType = model.GetType();
dynamic modelObject = Convert.ChangeType(model, modelType);
if (modelObject != null && modelType.GetMethod("Validate") != null)
{
modelObject.Validate(modelState);
}
}
if (!modelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse((HttpStatusCode)422, modelState);
}
//base.OnActionExecuting(actionContext);
}
}
}
[ValidationFilter]
public IHttpActionResult PostCustomer(CustomerModel model)
{
return Ok();
}