httpModule[2]

.NET Framework 开发员指南  

HttpModule

HttpModule 是实现 IHttpModule 接口和处理事件的程序集。ASP.NET 包含一组可由应用程序使用的 HttpModule 模块。例如,ASP.NET 提供了 SessionStateModule 来向应用程序提供会话状态服务。可以创建自定义 HttpModule 以响应 ASP.NET 事件或用户事件。

编写 HttpModule 的一般过程为:

  • 实现 IHttpModule 接口。
  • 处理 Init 方法并为所需事件进行注册。
  • 处理该事件。
  • 如果必须进行清理,还可根据需要实现 Dispose 方法。
  • 在 Web.config 中注册该模块。


.NET Framework 开发员指南  

自定义 HttpModule 示例

下面的自定义模块只是在任何 HTTP 请求的开头返回一个 Web 页消息和并在处理完该请求后返回另一个 Web 页消息。下面的 Init 函数为两个 HttpApplication 事件 BeginRequestEndRequest 注册事件处理程序。每个事件处理程序都编写为模块的私有方法。当已注册的事件被引发时,ASP.NET 将调用适当的处理程序方法,该方法写一个 Web 页然后返回。

[C#]
using System;
using System.Web;
using System.Collections;
public class HelloWorldModule : IHttpModule {
public String ModuleName {
get { return "HelloWorldModule"; }
}
// In the Init function, register for HttpApplication
// events by adding your handlers.
public void Init(HttpApplication application) {
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
application.EndRequest += (new EventHandler(this.Application_EndRequest));
}
// Your BeginRequest event handler.
private void Application_BeginRequest(Object source, EventArgs e) {
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.Write("<h1><font color=red>HelloWorldModule: Beginning of Request</font></h1><hr>");
}
// Your EndRequest event handler.
private void Application_EndRequest(Object source, EventArgs e) {
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.Write("<hr><h1><font color=red>HelloWorldModule: End of Request</font></h1>");
}
public void Dispose()
{
}
}

如下所示注册该模块:

<configuration>
<system.web>
<httpModules>
<!-- <add name="HelloWorldModule"
type="HelloWorldModule, HelloWorldModule" /> -->
</httpModules>
</system.web>
</configuration>
 
 
NET Framework 开发员指南  

ASP.NET 请求处理

ASP.NET 将 HTTP 请求映射到 HttpHandler。每个 HttpHandler 都能够处理应用程序中的单个 HTTP URL 或 URL 扩展组。HttpHandler 具有与 ISAPI 扩展相同的功能,但编程模型更简单。下表显示 ASP.NET 所提供的 HttpHandler 的示例。

处理程序说明
ASP.NET 页处理程序 (*.aspx) 用于所有 ASP.NET 页的默认 HttpHandler。
ASP.NET 服务处理程序 (*.asmx) 用于所有 ASP.NET 服务页的默认 HttpHandler。

HttpHandler 可以是同步或异步的。同步处理程序在完成对为其调用该处理程序的 HTTP 请求的处理后才会返回。异步处理程序通常启动可能很耗时的进程,并且在该进程完成前返回。

在编写和编译实现 HttpHandler 的代码以后,必须使用应用程序的 Web.config 文件注册该处理程序。

posted @ 2006-12-08 15:32  刘杨兵  阅读(224)  评论(0编辑  收藏  举报