You can use ActionFilter
. It is not global, but it moves the problem from your method body to the attribute. I understand that it does not completely solve your problem, but may be better than nothing.
public class ModelStateValidationActionFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { var modelState = actionContext.ModelState; if (!modelState.IsValid) actionContext.Response = actionContext.Request .CreateErrorResponse(HttpStatusCode.BadRequest, modelState); } }
And in your controller:
[HttpPost] [ModelStateValidationActionFilter] public IHttpActionResult Post(object model) { }
I believe that you can install it on your controller as well. I actually have not tried this, but could work accordingly .
[ModelStateValidationActionFilter] public class MyApiController : ApiController { }
EDIT:
As @Camilo Terevinto mentioned, Core is a little different. Just use this ActionFilter
if you want to use Core.
public class ModelStateValidationActionFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { var modelState = context.ModelState; if (!modelState.IsValid) context.Result = new ContentResult() { Content = "Modelstate not valid", StatusCode = 400 }; base.OnActionExecuting(context); } }
source share