1、创建HttpHandler
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace Handler
{
public class DownloadHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}public void ProcessRequest(HttpContext context)
{//context.Response.Write(context.Request.Url.ToString());
context.Response.Write("<h1><b>您没有权限访问此文件,请联系网站管理员!</b></h1>");
context.Response.End();}
}
}
2、配置iis,其中path处填写你要授权访问的文件类型,多个用‘,‘分割
<httpHandlers>
<add verb="*" path="*.rar" type="Hander.DownloadHander, Hander"/>
</httpHandlers>
3、在下载页面内添加如下方法
protected void Page_Load(object sender, EventArgs e)
{
//执行权限判断,如果拥有权限则执行下载bool b = IsCanDown();
if (b)
{
string path = Request.QueryString["file"] != null ? Request.QueryString["file"] : "/upload/day_20140312/留言板.rar";get_file(path);
}
}private bool IsCanDown()
{
//处理逻辑
return true;
}private void get_file(string path)
{
//string path = Request.QueryString["file"];
string filePath = Server.MapPath(path);//路径
string filename = Path.GetFileName(filePath);FileInfo fileInfo = new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
}