asp.net-mvc ASP.NET MVC 4 拦截所有传入请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11726848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC 4 intercept all incoming requests
提问by Jesse
Is there a way for me to catch allincoming requests to my ASP.NET MVC 4 app and run some code before continuing the request onward to the specified controller/action?
有没有办法让我捕获所有传入我的 ASP.NET MVC 4 应用程序的请求并在继续将请求转发到指定的控制器/操作之前运行一些代码?
I need to run some custom auth code with existing services, and to do this properly, I'll need to be able intercept all incoming requests from all clients to double check some things with the other service.
我需要使用现有服务运行一些自定义身份验证代码,并且要正确执行此操作,我需要能够拦截来自所有客户端的所有传入请求,以便与其他服务仔细检查某些内容。
回答by Yngve B-Nilsen
The most correct way would be to create a class that inherits ActionFilterAttributeand override OnActionExecutingmethod. This can then be registered in the GlobalFiltersin Global.asax.cs
最正确的方法是创建一个继承ActionFilterAttribute和覆盖OnActionExecuting方法的类。然后可以GlobalFilters在Global.asax.cs
Of course, this will only intercept requests that actually have a route.
当然,这只会拦截实际有路由的请求。
回答by M. Mennan Kara
You can use a HttpModule to accomplish this. Here is a sample I use to calculate the process time for all requests:
您可以使用 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 */ }
}
}
And this is how you register the module in Web.Config:
这就是您在 Web.Config 中注册模块的方式:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="PerformanceMonitorModule" type="Sample.HttpModules.PerformanceMonitorModule" />
</modules>
<//system.webServer>
回答by user2173353
I think that what you search for is this:
我认为您搜索的是:
Application_BeginRequest()
http://www.dotnetcurry.com/showarticle.aspx?ID=126
http://www.dotnetcurry.com/showarticle.aspx?ID=126
You put it in Global.asax.cs.
你把它放进去Global.asax.cs。
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Request.....;
}
I use this for debugging purposes but I am not sure how good solution it is for your case.
我将其用于调试目的,但我不确定它对您的情况有多好。
回答by Ogglas
I'm not sure about MVC4 but I think it is fairly similar to MVC5. If you have created a new web project -> look in Global.asaxand you should see the following line FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);in the method Application_Start().
我不确定 MVC4,但我认为它与 MVC5 非常相似。如果您创建了一个新的 Web 项目 -> 查看Global.asax,您应该FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);在方法中 看到以下行Application_Start()。
RegisterGlobalFiltersis a method in the file FilterConfig.cslocated in the folder App_Start.
RegisterGlobalFilters是FilterConfig.cs位于文件夹中的文件中的方法App_Start。
As @YngveB-Nilsen said ActionFilterAttributeis the way to go in my opinion. Add a new class that derives from System.Web.Mvc.ActionFilterAttribute. This is important because System.Web.Http.Filters.ActionFilterAttributewill fail with the following exception for example.
正如@YngveB-Nilsen 所说,这ActionFilterAttribute是我认为的方法。添加一个派生自System.Web.Mvc.ActionFilterAttribute. 这很重要,因为例如System.Web.Http.Filters.ActionFilterAttribute会因以下异常而失败。
The given filter instance must implement one or more of the following filter interfaces: System.Web.Mvc.IAuthorizationFilter, System.Web.Mvc.IActionFilter, System.Web.Mvc.IResultFilter, System.Web.Mvc.IExceptionFilter, System.Web.Mvc.Filters.IAuthenticationFilter.
给定的过滤器实例必须实现以下一个或多个过滤器接口:System.Web.Mvc.IAuthorizationFilter、System.Web.Mvc.IActionFilter、System.Web.Mvc.IResultFilter、System.Web.Mvc.IExceptionFilter、System.Web .Mvc.Filters.IAuthenticationFilter。
Example that writes the request to the debug window:
将请求写入调试窗口的示例:
public class DebugActionFilter : System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
Debug.WriteLine(actionContext.RequestContext.HttpContext.Request);
}
}
In FilterConfig-> RegisterGlobalFilters-> add the following line: filters.Add(new DebugActionFilter());.
在FilterConfig- > RegisterGlobalFilters- >添加以下行:filters.Add(new DebugActionFilter());。
You can now catch all incoming requests and modify them.
您现在可以捕获所有传入请求并对其进行修改。

