如何防止asp.net盜鏈下載問題的實現方法

來源:互聯網
上載者:User

有時在網路上經常碰到直接拷貝一個類似http://193.100.100.56/TestWebSolution/WebApplication1/test.rar地址準備下載test.rar檔案時,卻被告知沒有登入或者直接跳轉到其他頁面的情況,然後等登入後直接下載該檔案。要實現上面情況,在.NET世界裡是比較容易的。
1、首先建立一個類庫項目ClassLibrary1,實現如下(點這裡查看):
using System;
using System.Web;    // 引用System.Web組件
namespace ClassLibrary1
{
    public class MyHandler : IHttpHandler
    {
        public MyHandler()
        {
        }
        #region IHttpHandler 成員
        public void ProcessRequest(HttpContext context)
        {   // 跳轉到WebForm1.aspx,由WebForm1.aspx輸出rar檔案
            HttpResponse response = context.Response;
    response.Redirect("http://193.100.100.56/TestWebSolution/WebApplication1/WebForm1.aspx");
        }
        public bool IsReusable
        {   get
            {   // TODO:  添加 MyHandler.IsReusable getter 實現
  return true;
            }}
        #endregion
    }
}

2、建立測試用的Web項目WebApplication1。在設定檔Web.config檔案節點裡增加如下節點:

<httpHandlers>
  <add verb="*" path="*.rar" type="ClassLibrary1.MyHandler, ClassLibrary1" />
</httpHandlers>

3、在WebForm1.aspx裡增加一個文本為“下載”的Button,其Click事件如下(點這裡查看):

FileInfo file = new System.IO.FileInfo(@"G:\WebCenter\TestWebSolution\WebApplication1\test.rar");
// FileInfo 類在 System.IO 命名空間裡
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\v1.1.4322\aspnet_isapi.dll,在副檔名裡輸入“.rar”,然後確定即可。

5、在IE裡輸入http://193.100.100.56/TestWebSolution/WebApplication1/test.rar,會立即跳轉到http://193.100.100.56/TestWebSolution/WebApplication1/WebForm1.aspx,然後按WebForm1.aspx的“下載”按鈕就可以下載test.rar了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.