【IHttpHandler】使用IHttpHandler防盗链

本文介绍了一种在ASP.NET中实现防盗链的方法,通过自定义IHttpHandler来判断图片请求的来源,有效防止图片资源被盗用。具体实现包括在web.config中配置httpHandlers,以及创建myhandler类来处理jpg图片的请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     防盗链的原理,从图片请求的URL地址上判断是否是我们自己网站上的域名,如果不是,恭喜,你的图片已经被盗链了!

   那么我来介绍下图片放盗链的一个方法

  首先,添加个httpHandlers请求,webconfig部分配置节如下:

     <httpHandlers>
          <add verb="*" path="*.jpg" type="myhandler,App_Code"/>
    </httpHandlers>

然后添加个class,取名为myhandler继承于IHttpHandler

隐藏行号 复制代码 防盗链
  1. using System;
    
  2. using System.Data;
    
  3. using System.Configuration;
    
  4. using System.Web;
    
  5. using System.Web.Security;
    
  6. using System.Web.UI;
    
  7. using System.Web.UI.WebControls;
    
  8. using System.Web.UI.WebControls.WebParts;
    
  9. using System.Web.UI.HtmlControls;
    
  10. public class myhandler : IHttpHandler
    
  11. {
    
  12.     public void ProcessRequest(HttpContext context)
    
  13.     {
    
  14.         string FileName = context.Server.MapPath(context.Request.FilePath);
    
  15.         if (context.Request.UrlReferrer.Host == null)
    
  16.         {
    
  17.             context.Response.ContentType = "image/JPEG";
    
  18.             context.Response.WriteFile("~/images/no.png");//被替换图片
    
  19.         }
    
  20.         else
    
  21.         {
    
  22.             if (context.Request.UrlReferrer.Host.IndexOf("localhost") > -1)//这里是你的域名
    
  23.             {
    
  24.                 context.Response.ContentType = "image/JPEG";
    
  25.                 context.Response.WriteFile(FileName);
    
  26.             }
    
  27.             else
    
  28.             {
    
  29.                 context.Response.ContentType = "image/JPEG";
    
  30.                 context.Response.WriteFile("~/images/no.png");
    
  31.             }
    
  32.         }
    
  33.     }
    
  34.  
  35.     public bool IsReusable
    
  36.     {
    
  37.         get { return true; }
    
  38.     }
    
  39.  
  40.     public myhandler()
    
  41.     {
    
  42.  
  43.     }
    
  44. }
    
  45.  

myhandler继承自IHttpHandler实现了对url来源来判断jpg图片是否被盗链,本class中以localhost为例,修改localhost和images/no.png参数即可.

posted on 2015-01-09 00:01  v.e.n.u.s 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/jx270/p/4212233.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值