ASP.NET运行机制(二)--使用HttpModule,为每个请求附加额外信息

在之前的文章介绍过HttpModule,在这就不啰嗦了。

今天完成了一个小案例,效果如图:


为原有的文本,添加一些其它信息,实现思路如下:

一、创建TestHttpModule类,并实现IHttpModule接口。

二、实现IHttpModule接口中的方法,为HttpApplication对象的BeginRequest事件绑定方法,实现在用HttpHandler处理每个请求前,附加额外信息的功能。

namespace HttpModule_Demo.App_Code
{
    public class TestHttpModule : IHttpModule
    {
        public void Dispose() { }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += Context_BeginRequest;
            context.EndRequest += Context_EndRequest;
        }

        private void Context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            application.Response.Write("<p>HttpModule结束处理请求</p>");

        }

        private void Context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            application.Response.Write("<p>HttpModule开始处理请求</p>");

        }
    }
}

三、在web.config中配置TestHttpModule类。 

  <!--配置节点-->
  <system.webServer>
    <modules>
      <!--type="命名空间.类名"-->
      <add name="test" type="HttpModule_Demo.App_Code.TestHttpModule"/>
    </modules>
  </system.webServer>

四、创建两个aspx页面,并添加页面内容。

<body>
    <form id="form1" runat="server">
        <div>
            <h2>欢迎访问页面1</h2>
        </div>
    </form>
</body>
<body>
    <form id="form1" runat="server">
        <div>
            <h2>欢迎访问页面2</h2>
        </div>
    </form>
</body>

五、分别测试两个aspx页面,观察页面输出的内容。 

案例很简单,但是要理解它的流程。

扫描二维码关注公众号,回复: 1505427 查看本文章

其中有个小知识点,可以和大家分享下:

TestHttpModule实现IHttpModule接口时,它实现了二个方法,一个是Dispose,另一个是Init初始化方法。,下面的一段中“+=”个人理解,其实是一种多播委托,把Event事件连接在一起执行。

 
 
 context.BeginRequest += Context_BeginRequest;
            context.EndRequest += Context_EndRequest;
选择TestHttpModule类中的关键字BeginRequest并且转到定义(F12),会看到如下的代码。





猜你喜欢

转载自blog.csdn.net/qq_33857502/article/details/80597052
今日推荐