.NET防止地址栏直接下载,保护网站上文档、附件的方法
.net网站上上传的各类文档、附件,由于保密、版权等原因,不希望被未被授权的用户下载,同时登录了的用户可以根据授权进行下载,服务器如果不做特殊处理,只要知道了文档附件的实际地址,无法防止非法下载,网上介绍的改变IIS映射、修改web.config再自定义httphandler判断登录与否的方法操作复杂,不易实现,经对自己网站的研究,找到了一种比较方便实现的方法。
总体思路是:一、禁止相关文件夹内指定的文件类型可通过浏览器访问;二、使用一个下载模块通过物理地址以文件流的方式下载附件,同时可在下载模块中进一步判断权限。
一、禁止指定类型附件的访问
在指定文件夹(如:UploadFiles)内新建一个web.config文件,内容为:
<?xmlversion="1.0"encoding="UTF-8"?>
<configuration>
<system.webServer>
<security>
<requestFiltering>
<fileExtensions>
<addfileExtension=".rar"allowed="false"/>
<addfileExtension=".zip"allowed="false"/>
<addfileExtension=".xls"allowed="false"/>
<addfileExtension=".xlsx"allowed="false"/>
<addfileExtension=".docx"allowed="false"/>
<addfileExtension=".doc"allowed="false"/>
<addfileExtension=".pdf"allowed="false"/>
<addfileExtension=".swf"allowed="false"/>
<addfileExtension=".ceb"allowed="false"/>
</fileExtensions>
</requestFiltering>
</security>
</system.webServer>
</configuration>
这样UploadFiles文件夹内的上述扩展名的文件就不能通过浏览器直接访问了,如果是想对整个网站进行限制,以上内容就写入根部web.config相关的节,上面这些设置也可以在IIS管理器的“请求筛选”中完成。
二、使用下载模块处理下载
新建一个aspx程序downatt.aspx:
downatt.aspx代码:
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="downAtt.aspx.cs"Inherits="downAtt"%>
downatt.aspx.cs代码:
usingSystem;
publicpartialclassdownAtt:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
stringfilepath=Server.MapPath(Request.QueryString["file"]);//取文件“file”的物理路径
string[]filename1=filepath.Split('/');
stringfilename=filename1[filename1.Length-1];//取得文件名
System.IO.FileInfofile=newSystem.IO.FileInfo(filepath);
Response.Clear();
//Response.ContentEncoding=System.Text.Encoding.UTF8;
//添加头信息,为"文件下载/另存为"对话框指定默认文件名
Response.AddHeader("Content-Disposition","p_w_upload;filename="+Server.UrlEncode(filename));
//添加头信息,指定文件大小,让浏览器能够显示下载进度
Response.AddHeader("Content-Length",file.Length.ToString());
Response.ContentType="application/octet-stream";
//把文件流发送到客户端
Response.WriteFile(file.FullName);
//停止页面的执行
Response.End();
}
}
三、下载附件
通过downatt.aspx下载附件:
访问downatt.aspx?file=附件路径(如:uploadfile/a.doc)就可以下载了。
四、进一步设置
网站web.config中配置登录控制,
<authenticationmode="Forms">
<formsloginUrl="~/Login.aspx"name=".ASPXAUTH"defaultUrl="Default.aspx"timeout="30"path="/"/>//Login.aspx为登录模块
</authentication>
<authorization>
<denyusers="?"/>//禁止匿名用户访问
</authorization>
只要访问网站上的aspx等程序就必须登录,通过以上这些处理就有效地防止了指定的附件被非法下载。声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。