ASP.NET MVC: execute code for all actions (global OnActionExecuting?)

Is there a “global” OnActionExecuting that I can override so that all my MVC actions (regardless of the controller) do something when they are called? If so, how?

+5
source share
3 answers

Nope. The easiest way to do this is to write a common base class in which your entire class subclasses your controller, and then apply an action filter to that base class or override its OnActionExecuting () method.

+4
source

Asp.net MVC3 Added Support for Global Filters

From the ScottGu blog:

ASP.NET MVC "" , "". , , :

image

. ASP.NET MVC 3 , . , GlobalFilters. RegisterGlobalFilters() Global.asax , ( Application_Start()):

image

MVC 3 , , , (: http- ..). (DI).

+12

Create one class that implements IActionFilter and / or IResultFilter:

public class FilterAllActions : IActionFilter, IResultFilter
{      
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        throw new System.NotImplementedException();
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        throw new System.NotImplementedException();
    }

    public void OnResultExecuting(ResultExecutingContext filterContext)
    {
        throw new System.NotImplementedException();
    }

    public void OnResultExecuted(ResultExecutedContext filterContext)
    {
        throw new System.NotImplementedException();
    }
}

And register it on Global.asax

    protected void Application_Start()
    {
        //...
        RegisterGlobalFilters(GlobalFilters.Filters);
        //...
    }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new FilterAllActions());
    }
+2
source

All Articles