【IHttpHandler】使用IHttpHandler防盜鏈

來源:互聯網
上載者:User

標籤:

     防盜鏈的原理,從圖片請求的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.     public bool IsReusable
  35.     {
  36.         get { return true; }
  37.     }
  38.     public myhandler()
  39.     {
  40.     }
  41. }

myhandler繼承自IHttpHandler實現了對url來源來判斷jpg圖片是否被盜鏈,本class中以localhost為例,修改localhost和images/no.png參數即可.

【IHttpHandler】使用IHttpHandler防盜鏈

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.