如何使用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事件,并且通过这些事件的实现方法,将相关的信息打印出来。

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>");
%>
 



运行以后的界面如图所示:
Beginning of Request
This is the Page
End of Request


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值