HttpModule
HttpModule生命周期示意图
HttpRequest-->inetinfo.exe->ASPNET_ISAPI.DLL-->HttpPipeline-->ASPNET_WP.EXE-->HttpRuntime-->HttpApplicationFactory-->HttpApplication-->HttpModule-->HttpHandlerFactory-->HttpHandler-->HttpHandler.ProcessRequest()
如果想在中途截获httpRequest并做些自己的处理,就应该在HttpRuntime运行时内部来做到这一点,确切的说是在HttpModule这个容器中做到这个的。
系统本身的HttpModule实现一个IHttpModule的接口,当然我们自己的类也能够实现IHttpModule接口,这就可以替代系统的HttpModule对象了。
一个Http请求在被ASP.NETFramework捕获之后会依次交给HttpModule以及HttpHandler来处理。hm与hh之间不是完全独立的,实际上,http请求在hm传递的过程中会在某个事件内将控制权转交给hh的,而真正的处理在HttpHandler中执行完成后,HttpHandler会再次将控制权交还给HttpModule
IHttpHandler接口中最重要的方法ProcessRequest(HttpHandler用来处理Http请求),当一个Http请求经过由HttpModule容器传递到HttpHandler容器中的时候,framework会调用HttpHandler的ProcessRequest方法来做对这个Http请求做真正的处理。
framework实际上并不是直接把相关页面的HTTP请求定位到一个内部默认的IHttpHandler容器之上的,而是定位到了其内部默认的IHttpHandlerFactory上了。IHttpHandler Factory的作用就是对很多系统已经实现了的IHttpHandler容器进行调度和管理的,这样做的优点是大大增强了系统的负荷性,提升了效率。
IHttpModule执行在IHttpHandler前,有多个事件
context.BeginRequest += new EventHandler(Context_BeginRequest);//Asp.net处理的第一个事件,表示处理的开始
context.AuthenticateRequest += new EventHandler(Context_AuthenticateRequest); //验证请求,一般用来取得请求用户的信息
context.PostAuthenticateRequest += Context_PostAuthenticateRequest; //已经获取请求用户的信息
context.AuthorizeRequest += Context_AuthorizeRequest; //授权,一般用来检查用户的请求是否获得权限
context.PostAuthorizeRequest += Context_PostAuthorizeRequest; //用户请求已经得到授权
//context.ResolveRequestCache 获取以前处理缓存的处理结果,如果以前缓存过,那么,不必再进行请求的处理工作,直接返回缓存结果
//context.PostResolveRequestCache 已经完成缓存的获取操作
//context.PostMapRequestHandler 已经根据用户的请求,创建了处理请求的处理器对象
//context.AcquireRequestState 取得请求的状态,一般用于Session
//context.PostAcquireRequestState 已经取得了Session
//context.PreRequestHandlerExecute 准备执行处理程序
//context.PostRequestHandlerExecute 已经执行了处理程序
//context.ReleaseRequestState 释放请求的状态
//context.PostReleaseRequestState 已经释放了请求的状态
//context.UpdateRequestCache 更新缓存
//context.PostUpdateRequestCache 已经更新了缓存
//context.LogRequest 请求的日志操作
//context.PostLogRequest 已经完成了请求的日志操作
context.EndRequest += new EventHandler(Context_EndRequest);//本次请求处理完成
IHttpModule接口的声明:
public interface IHttpModule
{
void Init(HttpApplication context);
void Dispose();
}
我们可以自定义HttpModule实现此接口就行了
比如在init中增加一个事件
context.BeginRequest += new EventHandler(Context_BeginRequest);//Asp.net处理的第一个事件,表示处理的开始
然后对事件进行代码
private void Context_BeginRequest(object sender, EventArgs e) {
HttpApplication application = (HttpApplication)sender;//取得HttpApplicantion
HttpContext context = application.Context;//根据HttpApplication取得HttpContext
//context.Response.Redirect("http://www.baidu.com");//拦截进行跳转
application.Response.Write("Context_BeginRequest</br>");
}
然后进行web.config进行配置
老版本的配置如下
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
<!--VS2013之前/IIS7.0之前和经典模式 system.web下httpModules节点中-->
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
<add name="CustomerModule" type="MyTest_A.Module.CustomerModule,MyTest_A"/>
</httpModules>
<httpHandlers>
<add path="*.ckg" verb="*" type="MyTest_A.Common.CheckCodeHandle,MyTest_A"/>
</httpHandlers>
</system.web>
新版本的配置如下 目前应该都用如下的配置了
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<!--VS2013之后/IIS7.0之后和集成模式 system.webServer下modules节点中-->
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
<add name="CustomerModule" type="MyTest_A.Module.CustomerModule,MyTest_A"/>
<add name="TestModule" type="MyTest_A.Module.TestModule,MyTest_A"/>
</modules>
<handlers>
<add name="ckg" path="*.ckg" verb="*" type="MyTest_A.Common.CheckCodeHandle,MyTest_A"/>
</handlers>
</system.webServer>
name:模块名称,一般是类名
type:有两部分组成,前半部分是命名空间和类名组成的全名,后半部分是程序集名称,如果类是直接放在App_Code文件夹中,那程序名称是App_Code。
这样每个页面开始都会有个说明字符串显示了
HttpHandler
IHttpModule先执行IHttpHandler后执行
对请求的处理上:
IHttpModule是属于大小通吃类型,无论客户端请求的是什么文件,都会调用到它;例如aspx,rar,html的请求.
IHttpHandler则属于挑食类型,只有ASP.net注册过的文件类型(例如aspx,asmx等等)才会轮到调用它.
IHttpHandler按照你的请求生成响应的内容,IHttpModule对请求进行预处理,如验证、修改、过滤等等,同时也可以对响应进行处理 HttpHandler是HTTP请求的处理中心,真正地对客户端请求的服务器页面做出编译和执行,并将处理过后的信息附加在HTTP请求信息流中再次返回到HttpModule中
IHttpModule接口的声明:
public interface IHttpModule
{
void Init(HttpApplication context);
void Dispose();
}
下面我们自定义一个handle
用来显示下验证码,tip:如果要在handle中使用session 要用到IRequiresSessionState接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web.SessionState;
namespace MyTest_A.Common {
public class CheckCodeHandle: IHttpHandler, IRequiresSessionState {
public bool IsReusable
{
// Session 是可读写的对象,如果程序中需要写入 Session,要改成 true 才能写入,如果只是要读取的话,就可保持原来的 false
get { return true; }
}
private string GenerateCheckCode() {
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < 4; i++) {
number = random.Next();
//if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
//else
// code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
//Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
HttpContext.Current.Session["checkcode"] = checkCode;
return checkCode;
}
public void CreateCheckCodeImage(HttpContext context) {
string checkCode = context.Session["checkcode"].ToString();// "123456";
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics g = Graphics.FromImage(image);
try {
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = 0; i < 25; i++) {
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.GreenYellow), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Verdana", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//画图片的前景噪音点
for (int i = 0; i < 80; i++) {
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Red), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
context.Response.ClearContent();
context.Response.ContentType = "image/Gif";
context.Response.BinaryWrite(ms.ToArray());
}
finally {
g.Dispose();
image.Dispose();
}
}
public void ProcessRequest(HttpContext context) {
GenerateCheckCode();
CreateCheckCodeImage(context);
}
}
}
配置集成模式应在 <system.webServer>节点中如下 具体可以看上面httpmodule的web.config配置
<handlers>
<add name="ckg" path="*.ckg" verb="*" type="MyTest_A.Common.CheckCodeHandle,MyTest_A"/>
</handlers>
Verb属性:指定了处理程序支持的HTTP动作。*-支持所有的HTTP动作;“GET”-支持Get操作;“POST”-支持Post操作;“GET, POST”-支持两种操作。
Path属性:指定了需要调用处理程序的路径和文件名(可以包含通配符)。“*”、“*.aspx”、“showImage.aspx”、“test1.aspx,test2.aspx”
Type属性:用名字空间、类名称和程序集名称的组合形式指定处理程序或处理程序工厂的实际类型。ASP.NET运行时首先搜索bin目录中的DLL,接着在GAC中搜索。
这样我们就可以地址是如ckg结尾的就可以使用CheckCodeHandle来进行解析了如地址:
http://localhost/CheckCode/1.ckg 则出现了一个验证码图片