ASP.NET MVC 4拦截所有传入的请求

有没有办法让我赶上所有传入的请求到我的ASP.NET MVC 4应用程序并运行一些代码,然后再继续向指定的控制器/操作的请求?

我需要使用现有的服务运行一些自定义代码,为了做到这一点,我需要能够拦截来自所有客户端的所有传入请求,以检查其他服务的一些事情。

最正确的方法是创build一个inheritanceActionFilterAttribute并覆盖OnActionExecuting方法的类。 这可以在Global.asax.csGlobalFilters中注册

当然,这只会拦截实际有路线的请求。

你可以使用HttpModule来完成这个任务。 以下是我用来计算所有请求的处理时间的示例:

 using System; using System.Diagnostics; using System.Web; namespace Sample.HttpModules { public class PerformanceMonitorModule : IHttpModule { public void Init(HttpApplication httpApp) { httpApp.BeginRequest += OnBeginRequest; httpApp.EndRequest += OnEndRequest; httpApp.PreSendRequestHeaders += OnHeaderSent; } public void OnHeaderSent(object sender, EventArgs e) { var httpApp = (HttpApplication)sender; httpApp.Context.Items["HeadersSent"] = true; } // Record the time of the begin request event. public void OnBeginRequest(Object sender, EventArgs e) { var httpApp = (HttpApplication)sender; if (httpApp.Request.Path.StartsWith("/media/")) return; var timer = new Stopwatch(); httpApp.Context.Items["Timer"] = timer; httpApp.Context.Items["HeadersSent"] = false; timer.Start(); } public void OnEndRequest(Object sender, EventArgs e) { var httpApp = (HttpApplication)sender; if (httpApp.Request.Path.StartsWith("/media/")) return; var timer = (Stopwatch)httpApp.Context.Items["Timer"]; if (timer != null) { timer.Stop(); if (!(bool)httpApp.Context.Items["HeadersSent"]) { httpApp.Context.Response.AppendHeader("ProcessTime", ((double)timer.ElapsedTicks / Stopwatch.Frequency) * 1000 + " ms."); } } httpApp.Context.Items.Remove("Timer"); httpApp.Context.Items.Remove("HeadersSent"); } public void Dispose() { /* Not needed */ } } } 

这就是你如何在Web.Config中注册模块:

 <system.webServer> <modules runAllManagedModulesForAllRequests="true"> <add name="PerformanceMonitorModule" type="Sample.HttpModules.PerformanceMonitorModule" /> </modules> <//system.webServer> 

我认为你所search的是这样的:

 Application_BeginRequest() 

http://www.dotnetcurry.com/showarticle.aspx?ID=126

你把它放在Global.asax.cs

  protected void Application_BeginRequest(object sender, EventArgs e) { HttpContext.Current.Request.....; } 

我用它来进行debugging,但我不知道你的情况有多好的解决scheme。