Jes*_*sse 76 asp.net-mvc asp.net-mvc-4
有没有办法让我能够将所有传入的请求捕获到我的ASP.NET MVC 4应用程序并运行一些代码,然后再继续请求到指定的控制器/操作?
我需要使用现有服务运行一些自定义身份验证代码,并且要正确执行此操作,我需要能够拦截来自所有客户端的所有传入请求,以便使用其他服务仔细检查某些内容.
Yng*_*sen 79
最正确的方法是创建一个继承ActionFilterAttribute和override OnActionExecuting方法的类.然后可以在GlobalFilters中注册Global.asax.cs
当然,这只会拦截实际拥有路线的请求.
M. *_*ara 37
您可以使用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 */ }
}
}
Run Code Online (Sandbox Code Playgroud)
这就是你在Web.Config中注册模块的方法:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="PerformanceMonitorModule" type="Sample.HttpModules.PerformanceMonitorModule" />
</modules>
<//system.webServer>
Run Code Online (Sandbox Code Playgroud)
use*_*353 25
我认为你搜索的是这个:
Application_BeginRequest()
Run Code Online (Sandbox Code Playgroud)
http://www.dotnetcurry.com/showarticle.aspx?ID=126
你把它放进去了Global.asax.cs.
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Request.....;
}
Run Code Online (Sandbox Code Playgroud)
我用它来进行调试,但我不确定它对你的情况有多好.
| 归档时间: |
|
| 查看次数: |
64172 次 |
| 最近记录: |