摘要: 经常在网络上四处载东西,有时碰到直接拷贝一个类似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" />
< SPAN>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";
......[阅读全文]