IHttpHandler应用实例---防止图片盗链
实例来自《最优化Asp.net---面向对象开发实践》
imports System
imports System.Web
public class JpgHandler
implements IHttpHandler
public sub ProcessRequest(context as HttpContext)
dim FileName as string=context.Server.MapPath(context.request.FilePath)
if context.Request.UrlReferrer.Host is nothing then
context.Request.ContentType="image/JPEG"
context.Request.Response.WriteFile("/no.jpg")
else
if context.Request.UrlReferrer.Host.Indexof("mydomain.com")>0 then
context.Response.ContentType="image/JPEG"
context.Response.WriteFile(FileName)
else
context.Request.ContentType="image/JPEG"
context.Request.Response.WriteFile("/no.jpg")
end if
end if
end sub 
public readonly property IsReusable() as Boolean
get
return True
end get
end property
end class
首先识别被请求的图像文件名,在得知文件名后,判断Response对象的UrlReferrer属性(表示图片被引用的地址)是否为空,如果是,在意味着请求不是来自我们站点的某一个页面,因此设置响应的内容类型并使用Response对象的WriteFile方法来发送一个名为“/no.jpg”的图像。
如果引用存在,在下一步就判断引用路径是否包含我们站点的域名,如果是,在表明请求来自我们的站点,直接发送图像,否则,说明请求不是来自我们的站点,因此,提供一个替换的图像。
在梦想和现实之间寻找平衡 在欲望和理想之间左右的妥协!平淡又平凡的努力生活!


浙公网安备 33010602011771号