ASP.NET2.0防盜鏈

 

所謂盜鏈就是指其他網站把我們站點的文件鏈接帖到他們站上,這樣白白佔用我們的帶寬。訪問對於網站盜鏈行爲,是非常不道德的。要實現防盜鏈,我們就得在IIS處理URL時攔截。

效果圖:

未加防盜鏈之前:hm是我的機器名,用http://hm/myweb/default.aspxhttp://localhost/myweb/default訪問結果一樣。
這幅圖片是任人宰割的。

加了防盜鏈之後雖然還是同一個網站但是http://hm/myweb/default.aspx已經不能訪問那副花卉圖片,被以下圖片替代:

加了防盜鏈之後用localhost還是正常的!http://localhost/myweb/default訪問結果一樣。

原理:

其實hm是我的機器,但是由於服務器域名是localhost所以即使是同一個網站也不能訪問,所以就更別說
www.其他網站域名.com這樣的網站偷取我們的資源。關鍵就是IIS對所有的請求進行過濾看看是不是本站域名的。

全部代碼:

Web.Config
<?xml version="1.0"?>
<!--
    注意: 除了手動編輯此文件以外,您還可以使用
    Web 管理工具來配置應用程序的設置。可以使用 Visual Studio 中的
     “網站”->“Asp.Net 配置”選項。
    設置和註釋的完整列表在
    machine.config.comments 中,該文件通常位於
    /Windows/Microsoft.Net/Framework/v2.x/Config 中
-->
<configuration>
 <appSettings/>
 <connectionStrings/>
 <system.web>
    <httpHandlers>
      <add verb="*" path="*.jpg" type="myhandler,App_Code"/>
    </httpHandlers>
    <!--
            設置 compilation debug="true" 將調試符號插入
            已編譯的頁面中。但由於這會
            影響性能,因此只在開發過程中將此值
            設置爲 true。
        -->
  <compilation debug="true"/>
  <!--
            通過 <authentication> 節可以配置 ASP.NET 使用的
            安全身份驗證模式,
            以標識傳入的用戶。
        -->
  <authentication mode="Windows"/>
  <!--
            如果在執行請求的過程中出現未處理的錯誤,
            則通過 <customErrors> 節可以配置相應的處理步驟。具體說來,
            開發人員通過該節可以配置
            要顯示的 html 錯誤頁
            以代替錯誤堆棧跟蹤。

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
 </system.web>
</configuration>

 myhandler.cs  新建myhandler.cs 類時系統提示你要放入App_Code
using System;
using System.Web;

/// <summary>
/// myhandler 的摘要說明
/// </summary>

public class myhandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string FileName = context.Server.MapPath(context.Request.FilePath);
        if (context.Request.UrlReferrer.Host == null)
        {
            context.Response.ContentType = "image/JPEG";
            context.Response.WriteFile("~/no.gif");//被替換圖片
        }
        else
        {
            if (context.Request.UrlReferrer.Host.IndexOf("localhost") > -1)//這裏是你的域名
            {
                context.Response.ContentType = "image/JPEG";
                context.Response.WriteFile(FileName);
            }
            else
            {
                context.Response.ContentType = "image/JPEG";
                context.Response.WriteFile("~/no.gif");
            }
        }
    }
    public bool IsReusable
    {
        get { return true; }
    }
    public myhandler()
    {
    }
}

Default.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>清清月兒http://blog.csdn.net/21aspnet</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <img src="pic130.jpg" /></div>
    </form>
</body>
</html>

pic130.jpg

no.gif

IIS的配置:

配置應用程序擴展:添加一個.jpg的擴展!

注意:在本地的context.Request.UrlReferrer.Host就是localhost,
我開始以爲http://localhost/A/http://localhost/B/是不同的
context.Request.UrlReferrer.Host,那就是大錯特錯。http://localhost/A/http://localhost/B/的context.Request.UrlReferrer.Host都是localhost,所以測試一個用localhost,所以,本地測試用機器名例如我的是hm測試即可。經過處理後用機器名訪問就不行,雖然還是同一個站點,同一個文件,此處請多注意。

下面是怎麼防rar文件不從主站下載:方法和圖片類似,不過下載我們強迫他們到我們站點。

1、  首先創建一個類庫項目ClassLibrary1:

using System;

using System.Web;    // 引用System.Web組件

 

 

 public class MyHandler : IHttpHandler

 {

  public MyHandler()

  {

  }

 

  #region IHttpHandler 成員

  public void ProcessRequest(HttpContext context)

  {

   // 跳轉到WebForm1.aspx,由WebForm1.aspx輸出rar文件

   HttpResponse response = context.Response;

   response.Redirect("../manage/downloads.aspx");

  }

 

  public bool IsReusable

  {

   get

   {

    // TODO:  添加 MyHandler.IsReusable getter 實現

    return true;

   }

  }

  #endregion

 }

 

2、  在配置文件Web.config文件節點裏增加如下節點:

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

3、  在WebForm1.aspx裏增加一個文本爲“下載”的Button,其Click事件如下:

注意別忘記了using System.IO;

private void Button1_Click(object sender, System.EventArgs e)
  {
   FileInfo file = new System.IO.FileInfo(Server.MapPath("1.rar"));
   Response.Clear();

   Response.AddHeader("Content-Disposition", "filename=" + file.Name);

   Response.AddHeader("Content-Length", file.Length.ToString());

   string fileExtension = file.Extension;

 

   // 根據文件後綴指定文件的Mime類型

   switch (fileExtension)

   {

    case ".mp3":

     Response.ContentType = "audio/mpeg3";

     break;

    case "mpeg":

     Response.ContentType = "video/mpeg";

     break;

    case "jpg":

     Response.ContentType = "image/jpeg";

     break;

    case "........等等":

     Response.ContentType = "....";

     break;

    default:

     Response.ContentType = "application/octet-stream";

     break;

   }

 

   Response.WriteFile(file.FullName);

   Response.End();
 
  }

4、  最後一步就是在IIS裏增加一個應用程序擴展。在“默認網站”->“屬性”->“主目錄”->“配置”。在彈出的“應用程序配置”窗口裏按“添加”,在彈出的“添加/編輯應用程序擴展名映射”窗口裏“可執行文件”選擇C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/aspnet_isapi.dll,在擴展名裏輸入“.rar”,然後確定即可。

5、  在IE裏輸入http://localhost/web/1.rar,會立即跳轉到http://localhost/web/WebForm1.aspx,然後按WebForm1.aspx的“下載”按鈕就可以下載1.rar了。


 
發佈了11 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章