有時在網路上經常碰到直接拷貝一個類似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了。