gpt4 book ai didi

asp.net-mvc-3 - MVC 3 中的类似 BeginRequest 的过滤器?

转载 作者:行者123 更新时间:2023-12-03 22:22:30 25 4
gpt4 key购买 nike

我的应用程序中有一些代码需要在每个请求上执行,在执行任何其他操作之前 (甚至在身份验证之前)。到目前为止,我一直在使用 Application_BeginRequest我的 Global.asax 中的事件,并且效果很好。但是这段代码需要访问数据库,并且从 Global.asax 中执行此操作由于某种原因感觉不正确。此外,我正在使用的 Ninject.MVC3 nuget 不会将依赖项注入(inject)到我的 HttpApplication ctor 中。

所以我决定做的是把这段代码移到它自己的全局 Action 过滤器中。我现在遇到的问题是,无论我给这个过滤器使用什么 Order 或 FilterScope,我都无法让它先执行;我的授权过滤器总是胜过它。 MSDN似乎证实了这一点:

Filter Order

Filters run in the following order:

  1. Authorization filters
  2. Action filters
  3. Response filters
  4. Exception filters

For example, authorization filters run first and exception filters run last. Within each filter type, the Order value specifies the run order. Within each filter type and order, the Scope enumeration value specifies the order for filters.



我知道我可以使用 HttpModule,但这感觉不是很 MVCish,所以我试图在走这条路线之前用尽所有可能,这导致了我的问题:

全局操作过滤器是否有等效的 BeginRequest?

最佳答案

您可以在 Initialize 中执行此操作基本 Controller 的方法。

另一种可能性是注册 global filter :

public class MyGlobalFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// that's gonna be hit
}
}

RegisterGlobalFilters您的 Global.asax 的事件:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new MyGlobalFilter());
}

关于asp.net-mvc-3 - MVC 3 中的类似 BeginRequest 的过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4879336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com