自定义IHttpModule

时间:2023-03-08 18:33:28
自定义IHttpModule

HttpModule作用是 IIS将接收到的请求分发给相应的ISAPI处理前,先截获该请求。

通过这个我们可以完成很多额外功能。

自定义IHttpModule的例子:

通过自定义HttpModule,页面加载前劫持请求,向页面输入文字“MyModule”。

1.在asp.net站点下添加App_Code文件夹,然后添加MyModule类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web; namespace WebApplication4
{
public class MyModule:IHttpModule
{
public void Dispose()
{ } public void Init(HttpApplication context)
{
//context.BeginRequest是开始处理HTTP管线请求时发生的事件
context.BeginRequest += new EventHandler(context_BeginRequest);
//context.Error是当处理过程中发生异常时产生的事件
//context.Error += new EventHandler(context_Error);
} void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
HttpResponse response = context.Response;
response.Write("MyModule");
}
}
}

2.配置WebConfig。注册自定义IHttpModule

<?xml version="1.0" encoding="utf-8"?>

<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
http://go.microsoft.com/fwlink/?LinkId=169433
--> <configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" /> </system.web>
<system.webServer>
<modules>
<add name="MyModule" type="WebApplication4.MyModule,WebApplication4"/>
</modules>
</system.webServer> </configuration>
type值为DLL命名空间

3.运行网站,查看效果

自定义IHttpModule

4.可能遇到的错误:

未能从程序集“WebApplication4”中加载类型“WebApplication4.MyModule”。

请将MyModule.cs 文件生成操作设置为:编译。