在调用控制器方法之前执行代码?

Mat*_*zen 2 c# asp.net-mvc

是否有可能在动作方法本身在控制器上运行之前制作动作过滤器或运行的东西?

我需要这个来在动作运行之前分析请求中的一些值.

Iva*_*hos 10

您可以在控制器类中重写OnActionExecuting方法

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
        base.OnActionExecuting(filterContext);
//Your logic is here...
}
Run Code Online (Sandbox Code Playgroud)


Adr*_*ips 5

你可以使用一个属性:

public class MyFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Your logic here...

        base.OnActionExecuting(filterContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要将其应用于所有控制器,请在Global.asax.cs中:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new MyFilterAttribute());
}

protected void Application_Start()
{
    // Other code removed for clarity of this example...

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    // Other code removed for clarity of this example...
}
Run Code Online (Sandbox Code Playgroud)