mvc拦截请求IHttpModule

 

代码:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Diagnostics;

namespace TestMVCRoute
{
    public class myMVCHttpHandler :IHttpModule
    {
        public void Dispose()
        {
            /* Not needed */
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += OnBeginRequest;
            context.EndRequest += OnEndRequest;
            context.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");

        }




    }
}
复制代码

webconfig注册:

  <httpModules>
      <add name="myMVCHttpHandler" type="TestMVCRoute.myMVCHttpHandler"/>
  </httpModules>
</system.web>

或者节点:

<modules runAllManagedModulesForAllRequests="true">
      <add name="myMVCHttpHandler" type="TestMVCRoute.myMVCHttpHandler" />
    </modules>
</system.webServer>

ii6和ii7及以上注册节点结构不同需要注意,所以才贴出了两点。

 

改文章复制粘贴自:https://stackoverflow.com/questions/11726848/asp-net-mvc-4-intercept-all-incoming-requests

文章标题:ASP.NET MVC 4 intercept all incoming requests

不过前辈们建议,你最好分清你需要拦截的是什么请求,你的目的是什么,如果是在知情Action控制前拦截,那么你最好使用过滤器,而不是注册一个自定义的IHttpModule。

文章:msdn.microsoft.com/en-us/library/gg416513(VS.98).aspx 

 

或者也可以直接在Global.asax.cs文件中使用:

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

默认mvc的Global.asax.cs中没有Application_BeginRequest方法,但是自己复制粘贴过去会起作用,原理是什么还不清楚。

 

最建议的拦截mvc请求的方式还是用过滤器,

public class DebugActionFilter : System.Web.Mvc.ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext actionContext)
  {
     Debug.WriteLine(actionContext.RequestContext.HttpContext.Request);
  }
}

 

posted on   荆棘人  阅读(640)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2018-01-11 数据结构-B+树
2018-01-11 git可视化客户端
2018-01-11 学习榜样

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示