• Asp.Net中HttpModule的研究(转)


    HttpHandler实现了类似于ISAPI Extention的功能,他处理请求(Request)的信息和发送响应(Response)。HttpHandler功能的实现通过实现IHttpHandler接口来达到。而HttpModule实现了类似于ISAPI Filter的功能。

    HttpModule的实现

    HttpModules实现了类似于ISAPI Filter的功能,在开发上,通常需要经过以下步骤:

    1.编写一个类,实现IhttpModule接口

    2.实现Init 方法,并且注册需要的方法

    3.实现注册的方法

    4.实现Dispose方法,如果需要手工为类做一些清除工作,可以添加Dispose方法的实现,但这不是必需的,通常可以不为Dispose方法添加任何代码。

    5.在Web.config文件中,注册您编写的类

    下面是一个HttpModules的示例,在这个示例中,只是简单的注册了HttpApplication 的BeginRequest 和 EndRequest事件,并且通过这些事件的实现方法,将相关的信息打印出来。

    //例1:
    using System;
    using System.Web; //必需引用的名称空间
    namespace MyModule
    {
        public class MyModule : IHttpModule
          {
            public void Init(HttpApplication application)
              {
                  application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
                  application.EndRequest += (new EventHandler(this.Application_EndRequest));
              }
            private void Application_BeginRequest(Object source, EventArgs e)
              {
                  HttpApplication Application = (HttpApplication)source;
                  HttpResponse Response=Application.Context.Response;
                  Response.Write("<h1>Beginning of Request</h1><hr>");
              }
            private void Application_EndRequest(Object source, EventArgs e)
              {
                  HttpApplication application = (HttpApplication)source;
                  HttpResponse Response=Application.Context.Response;
                  Response.Write("<h1>End of Request</h1><hr>");
              }
            public void Dispose()
              {
              }
          }
    }

    MyModule类实现了IhttpModule接口。在Init方法中,指明了实现BeginRequest 和EndRequest 事件的方法。

    下面,在Web.config文件中注册这个类,就可以使用这个HttpModule了,注册的方法如下:

    <configuration>
          <system.web>
              <httpModules>
                  <add name=" MyModule " type=" MyModule, MyModule" />
              </httpModules>
          </system.web>
    </configuration>

    现在来看一下效果。编写一个Aspx页面test.aspx,内容如下:
    <%
    Response.Write("<h1>This is the Page</h1><hr>");
    %>

  • 相关阅读:
    mac Big Sur 安装MAT
    macOS Big Sur 设置JAVA_HOME
    redis geo叫车服务
    redis哈希和set无序集合联系
    redis备份主从模式
    Dapper操作Oracle数据库Clob字段
    策略模式示例
    跨域问题
    eclipse 代码提示无效
    数据库连接方式讲解
  • 原文地址:https://www.cnblogs.com/xuyuantao/p/1288811.html
Copyright © 2020-2023  润新知