How to set an action filter in all actions in ASP.NET MVC?

Is there a way to have an action filter like

public class MyActionFilterAttribute : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext context) {
    ...

automatically apply to all actions on the website?

+4
source share
4 answers

I do not believe that there is a ready-made way to do this. The easiest way to do this for simple sites is to simply apply a filter at the controller level. This is pretty common, and it's usually nice to have your own base controller class in case this happens when you want to extend it to all your controllers. For instance:.

[MyActionFilter]
public class MyBaseController : Controller
{
  ...
}

public class HomeController : MyBaseController
{
  ...
}

, , , . , , , .

+8

, , , ASP.NET MVC 3, .

+6
  • , .
  • , .
  • You can use the base controller class and override the OnActionExecuting method directly on the controller, which is probably more appropriate than using a filter if you intend to apply your filter code to all actions throughout the board.
+2
source

Where NewlyCreatedActionFilter is the ActionFilter you are creating, obviously. :)

[NewlyCreatedActionFilter]
public class Basecontroller : Controller
{
  ...
}

public class HomeController : BaseController
{
  ...
}

public class AccountController : BaseController
{
  ...
}

Both of these controller classes inherit from BaseController, so the NewlyCreatedActionFilter filter applies to all.

0
source

Source: https://habr.com/ru/post/1014454/


All Articles