防止盗链下载问题
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了。
?
6、? 當然,這里只按例子給個思路,完全可以再根據自身情況擴展。下面有幾個參考的資源文章:
l???????? http://www.9seek.com/news/show.aspx?id=745&cid=12
l???????? http://www.9seek.com/news/show.aspx?id=521&cid=12
l???????? http://www.9seek.com/news/show.aspx?id=520&cid=12
l???????? http://msdn.microsoft.com/asp.net/using/building/web/default.aspx?pull=/library/en-us/dnaspp/html/URLRewriting.asp
總結