Using ActionFilter
Action filters that are actually attributes can be registered as an attribute of an Action or a Controller, as illustrated in the following code snippet:
[HttpPost] [ValidateModel] // ActionFilter as attribute public ActionResult<Person> Post([FromBody] Person model) { // save the person return model; //just to test the action }
Here, we use ValidateModel
attribute that checks the ModelState
and returns BadRequestObjectResult
in case the ModelState
is invalid; we don't need to check the ModelState
in the actual Action.
To register action filters globally, you need to extend the MVC registration in the ConfigureServices
method of the Startup.cs
file, as follows:
builder.Services.AddControllersWithViews() .AddMvcOptions(options => { options.Filters.Add(new SampleActionFilter()); ...