【问题标题】:Run a method in each request in MVC, C#?在 MVC、C# 中的每个请求中运行一个方法?
【发布时间】:2012-03-01 06:11:40
【问题描述】:

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

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

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

【问题讨论】:

  • 你想在控制器上放置一个 ActionFilterAttribute
  • 我也会看看这个方法在做什么,如果 MVC 中仍然需要它,那么移植新技术已经过时的东西是没有意义的。
  • @tyrongower: CheckCookie() 必须检查客户端 cookie 并且可以访问会话!
  • 我构建了一个 ASP.NET Core 2 应用,使用 Razor Pages、Razor Pages,没有控制器吗?

标签: c# asp.net-mvc asp.net-mvc-3


【解决方案1】:

在 ASP.NET MVC 中,您可以编写 custom global action filter


更新:

根据 cmets 部分的要求,这里有一个此类过滤器的示例:

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

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

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

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

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

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

【讨论】:

  • 你能写一个样本吗?
  • @Mohammad,当然,我以为您阅读了我在答案中链接到的文章并尝试实现那里显示的示例代码。显然我的想法是错误的。所以我更新了我的答案来展示一个例子。
  • 谢谢老兄,但有个问题。我们如何重定向到MyActionFilterAttribute 中的操作?
  • @Mohammad,通过将RedirectToRouteResult 的实例分配给您的操作过滤器中的filterContext.Result 属性。
  • @DarinDimitrov:非常感谢您的回答。但是如果我创建一个从控制器继承的类并检查它的构造函数中的代码并从这个新类继承所有控制器呢?这是一个好主意吗?谢谢
【解决方案2】:

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

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

【讨论】:

  • 那么,我们可以通过上面的方法访问Cookie和Session吗?
  • 是的,你可以。但是这个方法可能在每个请求中执行不止一个
猜你喜欢
  • 1970-01-01
  • 2023-02-01
  • 2017-06-16
  • 1970-01-01
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
相关资源
最近更新 更多