继承IHttpModule拦截http请求

1,原理:浏览器请求-服务器-httpmodule-httphandler处理-浏览器

                 通过继承IHttpModule可以实现拦截http的请求,方面我们记录一些日志,过滤一些非法的请求,甚至实现代码的流量分流等等。

        小老弟们,在web应用程序中可以直接继承此接口;but,在类库需要引用system.web的dll文件。

2,示例:简单实现计算页面的加载时间

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CNKI.TPI.Web.Base
{
    public class CustHttpModule : IHttpModule
    {
        public void Init(HttpApplication application)//实现IHttpModules中的Init事件
        {
            //订阅两个事件
            application.BeginRequest += new EventHandler(application_BeginRequest);
            application.EndRequest += new EventHandler(application_EndRequest);
        }
        private DateTime starttime;
        private void application_BeginRequest(object sender, EventArgs e)
        {
            //object sender是BeginRequest传递过来的对象
            //里面存储的就是HttpApplication实例
            //HttpApplication实例里包含HttpContext属性
            starttime = DateTime.Now;
        }
        private void application_EndRequest(object sender, EventArgs e)
        {
            DateTime endtime = DateTime.Now;
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            //context.Response.Write("<p>页面执行时间:" + (endtime - starttime).ToString() + "</p>");
        }
        //必须实现dispose接口
        public void Dispose() { }
    }

}

3,在web.config注册

找到modles节点,撸上此代码,type是命名空间加类名

<system.webServer>
    <modules>
      
      <add name="CusHttpModule" type="Common.CusHttpModule"/>
    
    </modules>
  </system.webServer>

猜你喜欢

转载自blog.csdn.net/weixin_41609327/article/details/84943365
今日推荐