防止盗链下载问题
经常在网络上四处载东西,有时碰到直接拷贝一个类似 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文件节点里增加如下节点:
1<httphandlers>
2<add path="*.rar" type="ClassLibrary1.MyHandler, ClassLibrary1" verb="*"></add>
3
4httpHandlers>
5
63、 在WebForm1.aspx里增加一个文本为“下载”的Button,其Click事件如下(点这里查看):
7
8FileInfo file = new System.IO.FileInfo(@"G:\WebCenter\TestWebSolution\WebApplication1\test.rar");
9
10// FileInfo 类在 System.IO 命名空间里
11
12Response.Clear();
13
14Response.AddHeader("Content-Disposition", "filename=" + file.Name);
15
16Response.AddHeader("Content-Length", file.Length.ToString());
17
18string fileExtension = file.Extension;
19
20// 根据文件后缀指定文件的Mime类型
21
22switch (fileExtension)
23
24{
25
26case ".mp3":
27
28Response.ContentType = "audio/mpeg3";
29
30break;
31
32case "mpeg":
33
34Response.ContentType = "video/mpeg";
35
36break;
37
38case "jpg":
39
40Response.ContentType = "image/jpeg";
41
42break;
43
44case "........等等":
45
46Response.ContentType = "....";
47
48break;
49
50default:
51
52Response.ContentType = "application/octet-stream";
53
54break;
55
56}
57
58Response.WriteFile(file.FullName);
59
60Response.End();
61
62
63
64
65
664、 最后一步就是在IIS里增加一个应用程序扩展。在“默认网站”->“属性”->“主目录”->“配置”。在弹出的“应用程序配置”窗口里按“添加”,在弹出的“添加/编辑应用程序扩展名映射”窗口里“可执行文件”选择C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_isapi.dll,在扩展名里输入“.rar”,然后确定即可。
67
685、 在IE里输入 http://193.100.100.56/TestWebSolution/WebApplication1/test.rar ,会立即跳转到 http://193.100.100.56/TestWebSolution/WebApplication1/WebForm1.aspx ,然后按WebForm1.aspx的“下载”按钮就可以下载test.rar了。
69
706、 当然,这里只按例子给个思路,完全可以再根据自身情况扩展。下面有几个参考的资源文章:
71
72l http://www.9seek.com/news/show.aspx?id=745&cid=12
73
74l http://www.9seek.com/news/show.aspx?id=521&cid=12
75
76l http://www.9seek.com/news/show.aspx?id=520&cid=12
77
78l http://msdn.microsoft.com/asp.net/using/building/web/default.aspx?pull=/library/en-us/dnaspp/html/URLRewriting.asp</httphandlers>