IHttpHandler是ASP.NET处理实际操作的接口。在MSDN是这样定义的:使用自定义的HTTP处理程序同步处理HTTP Web请求而实现的协定。(注意:这里写的很清楚是同步HTTP请求如果是异步的话就要使用IHttpAsyncHandler接口程序了)。他包含一个属性IsReusable用于获取当前IHttpHandler实例是否可用一般设置为True.一个方法ProcessRequest(HttpContext context)进行实际的操作过程。
自定义IHttpHandler
使用自定义的IHttpHandler处理程序需要三步
1)定义一个实现了IHttpHandler接口的类。
2)在Web.config文件中注册这个类
3)执行相应的HttpRequst
下面是一个图片防盗链接的实例:
01 |
public class LinkProtectHandler: IHttpHandler |
03 |
#region IHttpHandler 成员 |
05 |
public bool IsReusable |
10 |
public void ProcessRequest(HttpContext context) |
14 |
string fileName = context.Server.MapPath(context.Request.FilePath); |
16 |
if (context.Request.UrlReferrer.Host== null ) |
18 |
context.Response.ContentType = "image/JPEG" ; |
19 |
context.Response.WriteFile( "/LinkProtect.jpg" ); |
24 |
if (context.Request.UrlReferrer.Host.IndexOf( "mydomain.com" )>0) |
26 |
context.Response.ContentType = "image/JPEG" ; |
27 |
context.Response.WriteFile(fileName); |
31 |
context.Response.ContentType = "image/JPEG" ; |
32 |
context.Response.WriteFile( "/LinkProtect.jpg" ); |
2 |
< remove verb = "*" path = "*.asmx" /> |
3 |
< add verb = "*" path = "*.asmx" validate = "false" type = "System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> |
4 |
< add verb = "*" path = "*.jpeg" validate = "false" type = "WebApplication3.LinkProtectHandler,WebApplication3" /> |
自定义IHttpHandlerFactory
IHttpHandlerFactory在MSDN中是这样定义的:定义类工厂为创建新的IHttpHandler对象而必须实现的协定。他包含2个接口方法,GetHandler():返回实现IHttp接口的类的实例。ReleaseHandler():始工厂可以重复使用现有的处理程序实例。这个接口就是可以把很多实现IHttpHandler接口的方法放在Factory中在Web.config注册时主要注册这个类即可,在使用的时候交由Factory进行判断到底使用哪个IHttpHandler实例。
01 |
public class CustomerHttpHandlerFactory:IHttpHandlerFactory |
04 |
#region IHttpHandlerFactory 成员 |
06 |
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) |
09 |
string path = context.Request.PhysicalPath; |
11 |
string exstention = Path.GetExtension(path); |
13 |
if (exstention== ".rss" ) |
15 |
return new RssHandler(); |
17 |
else if (exstention== ".atmo" ) |
19 |
return new ATMOHandler(); |
27 |
public void ReleaseHandler(IHttpHandler handler) |
在Web.Config里面进行如下定义:
2 |
< remove verb = "*" path = "*.asmx" /> |
3 |
< add verb = "*" path = "*.rss,*.atom" validate = "false" type = "WebApplication3.CustomerHttpHandlerFactory,WebApplication3" /> |
IHttpAsyncHandler异步接口
IHttpAsyncHandler在MSDN中是这样描述的:定义 HTTP 异步处理程序对象必须实现的协定。他包含3个方法:
BeginProcessRequest:启动对 HTTP 处理程序的异步调用,EndProcessRequest:进程结束时提供异步处理 End 方法。ProcessRequest:通过实现 IHttpHandler 接口的自定义 HttpHandler 启用 HTTP Web 请求的处理。 (继承自 IHttpHandler。)和一个IsReusable属性。