Filter to Secure an Action Method
Learn about applying cross-functional filters at different levels in ASP.NET Core MVC, enabling role management, and creating roles programmatically.
Cross-functional filters
When we need to add functionality to multiple controllers and actions, we can use or define our filters implemented as an attribute class. Filters can be applied at the following levels:
At the action level, by decorating an action method with the attribute. This will only affect one action method.
At the controller level, by decorating the controller class with the attribute. This will affect all methods of the controller.
At the global level, by adding the attribute type to the Filters collection of the
MvcOptions
instance that can be used to configure MVC when calling theAddControllersWithViews
method, as shown in the following code:
builder.Services.AddControllersWithViews(options =>{options.Filters.Add(typeof(MyCustomFilter));});
Using a filter to secure an action method
We might want to ensure that members of certain security roles can only call one particular action method of a controller class. We do this by decorating the method with the [Authorize]
attribute, as described in the following list:
...