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开发者_如何学C 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.
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:
Filter Order
Filters run in the following order:
- Authorization filters
- Action filters
- Response filters
- 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.
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:
Is there a BeginRequest equivalent for global action filters?
You could do this in the Initialize method of a base controller.
Another possibility is to register a global filter:
public class MyGlobalFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// that's gonna be hit
}
}
and in the RegisterGlobalFilters
event of your Global.asax
:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new MyGlobalFilter());
}
精彩评论