web developer tips (43):通过请求处理管道注册IHttpModule

原文地址:The way you register your IHttpModule depends on the request processing pipeline in which your module will run

建立和运行自定义IHttpModule需要做三件简单的事:
1、把源码编译成dll。
2、在net里注册。
3、在IIS配置系统里注册。

http://www.watch-life.net/visual-studio/register-your-ihttpmodule-depends-on-the-pipeline.html

1)假定你有个简单的模块,在验证发生之前,触发一个用HttpContext 做参数的事件,在BeginRequest事件写如下代码:

public void Init(HttpApplication context)
{
context.BeginRequest += new System.EventHandler(context_BeginRequest);
}

public void Dispose() { }

public class PreAuthEventArgs : EventArgs
{
public HttpContext httpContext;

public PreAuthEventArgs(HttpContext context)
{
httpContext = context;
}
}

public delegate void PreAuthRequestEventHandler(object sender, PreAuthEventArgs e);
public event PreAuthRequestEventHandler PreAuthEvent;

void context_BeginRequest(object sender, System.EventArgs e)
{
if (PreAuthEvent != null)
{
PreAuthEvent(this, new PreAuthEventArgs(HttpContext.Current));
}
}
}

把模块编译成dll文件,在Visual Studio里右键单击项目,选择属性,在“应用”标签页的输出项选择“类库”
image

2)在网站里,有两个方法注册dll:

A)用GAC注册。为此你需要要有管理员权限。使用Global Assembly Cache Tool(Gacutil.exe)添加程序集到GAC:

gacutil /if YouModule.dll

你可以在项目编译的任何时候来注册GAC,在项目属性里的“生成事件”里可以完成程序集的GAC注册,在“生成后事件执行命令行”里输入:

<path to gacutil> /if $(TargetPath)
 

clip_image002

B)然而,最常用的解决方法是,在网站的bin目录替换dll,通过这个方法不会打破通过xcopy部署网站的方式。

3)最后,需要把模块注册到IIS的配置系统里。整个这篇文章的目的就是说明,当网站在执行的中的时候,通过管道(pipeline )注册模块有什么不同。
IIS7的推出了集成模式的概念,要求集成处理使用IIS和ASP.Net请求处理管道。在IIS6中,IIS和ASP.NET请求管道是独立的,在在IIS7中是向后兼容的经典模式。如果你的网站或应用程序是执行的经典模式,或在IIS6的服务器运行,则需要注册不同的模块。

IIS6和IIS7的经典模式,在web.config里注册模块 ,代码如下:

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

在IIS7的集成模式,web.config代码如下:

<configuration>
  <system.webServer>
    <modules>
      <add name="AuthenticationCheckerModule " type="AuthenticationCheckerModule "/>
    </modules>
  </system.webServer>
</configuration>
 

有关更多注册HTTP 模块的详细内容见:Creating and Registering a Custom HTTP Module



微信扫描下方的二维码阅读本文

那年今日

2007-09-06 苏格拉底对失恋者说的话 (0 个评论)

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注