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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9511462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:42:22  来源:igfitidea点击:

Run a method in each request in MVC, C#?

c#asp.net-mvcasp.net-mvc-3

提问by Mohammad Dayyan

In WebForm we could write a method in MasterPage.cs and it ran in each request .
e.g:

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

MasterPage.cs
--------------
protected void Page_Load(object sender, EventArgs e)
{
   CheckCookie();
}

How can we do something like this in MVC ?

我们如何在 MVC 中做这样的事情?

采纳答案by Darin Dimitrov

In ASP.NET MVC you could write a custom global action filter.

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



UPDATE:

更新:

As requested in the comments section here's an example of how such filter might look like:

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

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

If you want to perform authorization based on the value of the cookie, it would be more correct to implement the IAuthorizationFilterinterface:

如果想根据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();
        }
    }
}

If you want this action filter to run on each request for each controller action you could register it as a global action filter in your global.asax in the RegisterGlobalFiltersmethod:

如果您希望此操作过滤器在每个控制器操作的每个请求上运行,您可以在 global.asaxRegisterGlobalFilters方法中将其注册为全局操作过滤器:

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

And if you need this to execute only for particular actions or controllers simply decorate them with this attribute:

如果您只需要对特定操作或控制器执行此操作,只需使用此属性装饰它们:

[MyActionFilter]
public ActionResult SomeAction()
{
    ...
}

回答by ionden

You could use Global.asax Application_AcquireRequestStatemethod which will get called on every request:

您可以使用 Global.asaxApplication_AcquireRequestState方法,该方法将在每个请求中调用:

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
     //...
}