且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止直接访问 asp.net 中的文件和文件夹?

更新时间:2023-12-02 08:07:34

问题是 .pdf 扩展名没有被 ASP.NET 处理程序捕获,因为它不是一个文件映射到 ASPNET_ISAPI 的类型(又名 ASP.NET HTTP 运行时).因此,web.config 文件中的过滤不适用于这些文件.

您有两个选择:

  1. 使用 IIS 配置面板将所有文件扩展名(或至少在这种情况下为 pdf 文件)映射到 ASPNET_ISAPI.请注意,这会增加服务器的负载,因为 IIS 本身的开销低于 IIS + ASP.NET;
  2. 使用为您获取文件的 HTTP 处理程序.这也允许您对文件访问进行一些细粒度的授权检查.请参阅HTTP 处理程序简介.

I have deployed a web application on IIS7 and the application has mail attachment files saved on webserver's Attachments folder and it's working fine when the attachment is downloaded from application.

The problem is when the same url viewed from Chrome is typed from a different machine the same can be viewed/downloaded. I tried couple of solution after googling but here the Attachments folder on webserver have security enabled for Network services.

http://machine-121/AdminManagement/Attachments/58501/17112014131251/FilledForm.pdf (can be read)

I tried

<configuration>
<system.web>
<authentication mode="Forms"/>
<authorization>
<deny users="?"/>  <!--This will restrict anonymous user access-->
</authorization>
</system.web>
<location path="login.aspx"> <!-- Path of your Registration.aspx page -->
<system.web>
<authorization>
<allow users="*"/> <!-- This will allow users to access to everyone to Registeration.aspx--> 
</authorization>
</system.web>
</location>
</configuration>

but couldn't succeed any suggestion/help would be of great help.

The problem is that the .pdf extension isn't caught by the ASP.NET handlers, since that isn't a file type that is mapped to ASPNET_ISAPI (aka the ASP.NET HTTP Runtime). Hence the filtering in your web.config file doesn't apply to those files.

You have two options:

  1. Map all file extensions (or at least pdf files in this case) to ASPNET_ISAPI using the IIS configuration panel. Note that this will increase the load on your server since the overhead of IIS on itself is lower than IIS + ASP.NET;
  2. Use an HTTP handler that gets the file for you. This allows you to do some fine grained authorization checks on the file access too. See the Introduction to HTTP Handlers.