在MVC 3的BeginRequest状过滤器? [英] BeginRequest-like filter in MVC 3?

查看:149
本文介绍了在MVC 3的BeginRequest状过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序之前,什么都执行一些code,我需要在每次请求执行, (甚至是身份验证之前)。到目前为止,我一直在用我的Global.asax中的Application_BeginRequest 事件,这已正常工作。但是,这code需要访问数据库,并从Global.asax中这样做感觉不对出于某种原因。另外,我使用的是Ninject.MVC3的NuGet不会把依赖注入我的HttpApplication构造函数。

I have some code in my application that I need to execute on every request, before anything else executes (even before authentication). So far I've been using the Application_BeginRequest event in my Global.asax, and this has worked fine. But this code needs to hit the database, and doing this from Global.asax doesn't feel right for some reason. Also, the Ninject.MVC3 nuget I'm using won't inject dependencies into my HttpApplication ctor.

所以我决定做的是移动这个code到自己的全球行动的过滤器。我现在遇到的问题是,无论什么样的顺序或FilterScope我给这个过滤器,我不能让它执行第一;我的授权过滤器总是胜过它。 MSDN 似乎证实了这一点:

So what I decided to do is move this code into its own global action filter. The problem I'm having now is that no matter what Order or FilterScope I give this filter, I can't get it to execute first; my authorization filter always beats it. MSDN seems to confirm this:

过滤器顺序

过滤器运行下面的命令:

Filters run in the following order:


      
  1. 授权过滤器

  2.   
  3. 动作过滤器

  4.   
  5. 响应滤波器

  6.   
  7. 异常过滤器

  8.   

例如,授权过滤器运行
  第一和异常运行滤波器去年。
  在每个过滤器类型,订单
  值指定运行顺序。中
  每个过滤器类型和顺序,范围
  枚举值指定的顺序
  对于过滤器。

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 的,所以我想才去这条路线,这导致了我的问题用尽所有possiblities:

I know I can use an HttpModule, but that doesn't feel very MVCish, so I am trying to exhaust all possiblities before going that route, which leads to my question:

是否有一个的BeginRequest相当于全球行动过滤器?

推荐答案

您可以在这样做的<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.initialize.aspx\">Initialize一个基本控制器的方法。

You could do this in the Initialize method of a base controller.

另一种可能性是注册一个<一href=\"http://odeto$c$c.com/Blogs/scott/archive/2011/01/15/configurable-global-action-filters-for-asp-net-mvc.aspx\">global过滤器:

Another possibility is to register a 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());
}

这篇关于在MVC 3的BeginRequest状过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆