IHttpHandler应用实例---防止图片盗链

实例来自《最优化Asp.net---面向对象开发实践》

imports  System
imports  System.Web

public   Class JpgHandler class JpgHandler
   
implements IHttpHandler
   
public Sub ProcessRequest()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()property IsReusable() as Boolean
       
get
          
return True
       
end get
   
end property
 
end class


首先识别被请求的图像文件名,在得知文件名后,判断Response对象的UrlReferrer属性(表示图片被引用的地址)是否为空,如果是,在意味着请求不是来自我们站点的某一个页面,因此设置响应的内容类型并使用Response对象的WriteFile方法来发送一个名为“/no.jpg”的图像。

如果引用存在,在下一步就判断引用路径是否包含我们站点的域名,如果是,在表明请求来自我们的站点,直接发送图像,否则,说明请求不是来自我们的站点,因此,提供一个替换的图像。

转载于:https://www.cnblogs.com/sonrain/archive/2008/07/17/1244936.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值