Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Model state validation filter ASP.NET Core
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Example
{
public class ModelStateValidationFilter : Attribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid) {
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
public void OnActionExecuted(ActionExecutedContext context) {}
}
}
@TimHolzherr
Copy link

TimHolzherr commented Feb 24, 2021

Instead of creating your own ModelStateValidationFilter one could use the build in ModelStateInvalidFilter.
This filter is automatically registered on your controller if you decorate it with the ApiController attribute. The ApiController Attribute will enable additional api specific behaviors which are documented in the link above. To apply the ApiController attribute to all controllers in your assembly one can decorate the Assembly itself with the attribute. Just add the following code to a *.cs file which is part of the assembly.

using Microsoft.AspNetCore.Mvc;

[assembly: ApiController]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment