asp.net 安全---File Sytem 安全

本文介绍如何安全地在Web应用中访问指定文件夹内的文件,并通过设置MIME类型来限制文件类型,确保只允许特定类型的文件被访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. How to access existing files safely 

       

 FileInfo file = new FileInfo(Path.Combine(。。。。。 在网站中如果使用get方法进行传递文件名称的时候,比如:http://localhost:4245/WebSite2/getfile.aspx?filename=example2.容易被攻击 如http://localhost:4245/WebSite2/getfile.aspx?filename=web.config 也可以http://localhost:4245/WebSite2/getfile.aspx?filename=http://www.cnblogs.com/Win.ini 以获取系统的其他配置信息,这样危险呢 ,

    使用FileInfo file = new FileInfo(Server.MapPath(filename));就不会出现这个问题了 因为 Server.MapPath will not return any path outside of the root of your Web application

  要把要访问的文件控制在一个文件夹内,就不会出现访问WEB.config的问题了 需要的做法是,首先建立一个文件夹 如:Document

     FileInfo file = new FileInfo(Server.MapPath(Path.Combine("documents", filename))); 

 这样整个文件的访问,就不会跳出Document这个文件夹范围内了 

 

            如何控制访问文件的类型?通过设置 MIME类型来实现。

            Response.ContentType = "text/plain";

如果要访问的文件不在root范围之内,则需要使用绝对路径

    FileInfo file = new FileInfo(Server.MapPath(Path.Combine(@"c:\inetpub\documents\", filename))); 

 

在获得了文件之后,不是把他们response.write到页面,而是下载

Response.AddHeader("Content-Disposition", "attachment; filename=&"+ filename); 

 

如果你需要对别人下载的权限进行判断,只需要在web.config中

?<xml version="1.0" encoding="utf-8"? >
<configuration >
<system.web >
<authentication mode="Forms" / >
<authorization >
<allow roles="GoldMember" / >
<deny users="*" / >
</authorization >
</system.web

</configuration > 

设置系统的访问角色,然后在下载的时候执行

if (User.IsInRole("GoldMember"))
{
// Serve content

 如果必须要控制下载的是通过本网站的话 可以使用以下的语句

if (Request.UrlReferrer.Host != "mysite.example"& &
Request.UrlReferrer.Host != "www.mysite.example")
{
Response.End();
}
else
{
// Continue

 

在使用上传文件的时候在web.config中加入

?<x ml version="1.0 ” ?
<c onfiguration >
....
< system.web >
< httpRuntime
executionTimeout = "90 “
maxRequestLength="4096 “
/ >
....
< /system.web >
....
</ configuration >

Handling User Uploads ❘ 223 

转载于:https://www.cnblogs.com/SumYang/archive/2011/03/26/1996084.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值