I have a bunch of controllers that have the [AllowAnonymous] attribute in class-level scope. I need to check a few things before any of the actions in such controllers executes. For example, I might do something like this:
[AllowAnonymous]
public class MyController : Controller
{
[HttpGet]
public ActionResult Index()
{
// do some preliminary work
// run action-specific code
}
}
Because I have many such controllers and actions, copy-pasting the same code is a tedious process. Is there a way to execute this preliminary code for every anonymous action in a much simpler way?
You can create your own action filter.
Make a class that inherits
ActionFilterAttributeand overridesOnActionExecuting.Apply that attribute to a controller or action and it will run before every request to that controller or action.