在MVC,C#中的每个请求中运行一个方法?

Moh*_*yan 47 c# asp.net-mvc asp.net-mvc-3

在WebForm中,我们可以在MasterPage.cs中编写一个方法,并在每个请求中运行.
例如:

MasterPage.cs
--------------
protected void Page_Load(object sender, EventArgs e)
{
   CheckCookie();
}
Run Code Online (Sandbox Code Playgroud)

我们怎么能在MVC中做这样的事情?

Dar*_*rov 93

在ASP.NET MVC中,您可以编写自定义全局操作筛选器.


更新:

根据评论部分的要求,这里有一个示例,说明这种过滤器的外观如何:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var fooCookie = filterContext.HttpContext.Request.Cookies["foo"];
        // TODO: do something with the foo cookie
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要根据cookie的值执行授权,那么实现IAuthorizationFilter接口会更正确:

public class MyActionFilterAttribute : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var fooCookie = filterContext.HttpContext.Request.Cookies["foo"];

        if (fooCookie == null || fooCookie.Value != "foo bar")
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果希望此操作筛选器针对每个控制器操作的每个请求运行,则可以将其注册为RegisterGlobalFilters方法中global.asax中的全局操作筛选器:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new MyActionFilterAttribute());
}
Run Code Online (Sandbox Code Playgroud)

如果您只需要执行特定操作或控制器,只需使用以下属性进行装饰:

[MyActionFilter]
public ActionResult SomeAction()
{
    ...
}
Run Code Online (Sandbox Code Playgroud)


ion*_*den 7

您可以使用Global.asax Application_AcquireRequestState方法,该方法将在每个请求上调用:

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
     //...
}
Run Code Online (Sandbox Code Playgroud)

  • 那么,我们可以从上面的方法访问Cookie和Session吗? (2认同)
  • 是的你可以。但此方法可能会在每个请求中执行多次 (2认同)