httpHandler 是特别类的一种,可以处理对特定类型文件的请求。实际上甚至可以通过创建自己的处理器来处理对.aspx 页面的请求,将整个页面的处理系统换掉。下面我们就用HttpHandler 来防止图片盗链。
代码:
using System; using System.Web;
namespace HttpHandlerDemo { public class JpgHandler:IHttpHandler { #region IHttpHandler 成员
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context) { string fileName = context.Request.FilePath; if (context.Request.UrlReferrer.Host == null) { context.Response.ContentType = "image/JPEG"; context.Response.WriteFile("/no.jpg"); } else { if (context.Request.UrlReferrer.Host.IndexOf("localhost") >= 0) { context.Response.ContentType = "image/JPEG"; context.Response.WriteFile(fileName); } else { context.Response.ContentType = "image/JPEG"; context.Response.WriteFile("/no.jpg"); } } }
#endregion } }
|
为了ASP.NET能和HttpHandler 通信,必须实现 IHttpHandler 接口的所有成员。
1、 ProcessRequest() 方法是处理请求并作出响应的地方。
2、 IsReusable 属性告诉 ASP.NET 是否该 HttpHandler 实例能被多个请求复用,或者它是否应每次都创建一个新的实例。通常该属性设为 true 。设为 false 的场景为,希望当某个用户的特定操作在处理器中发生时不希望下一位用户接着使用。
做完了上面的工作,还需要在 web.config 文件中相关部分添加该 HttpHandler 到应用程序中。
格式如下:
<httpHandlers> <add verb="*" path="*.jpg"type="MyClass,MyDll"/> </httpHandlers> |
Verb 属性表明了包含的请求类型(GET、POST)可以使用通配符 “*” 表示接受所有请求。
Path 描述了请求文件的路径。
Type 指定了实现 IHttpHandler 的类,以及其所在程序集名称。这里要注意的是类名必须是完全名称,即需要包括命名空间。