如何拒绝通过浏览器访问目录内容(IIS 服务站点)

How to deny access to directory contents (IIS served site) via browser

我在 SiteFolder/ 中保存了一些文件,我需要通过 C# 项目访问这些文件,但我不希望它们通过浏览器在这些路径中列出。我怎样才能做到这一点? IIS 中是否有任何可以更改的设置?

此外,由于我将 access/read/write 这个目录文件的完全控制权授予了 IIS 用户,那么解决方案是什么?

基本上我不希望任何人通过浏览器访问此目录的内容,但应该可以通过 IIS 访问。

提前致谢。

编辑 1:这是文件写入功能,应该不受影响 -

FileStream file = new FileStream(Server.MapPath("~/SiteFolder/example.txt"), FileMode.Append, FileAccess.Write, FileShare.Write);
using (StreamWriter fileWriter = new StreamWriter(file))
{
     fileWriter.WriteLine("Something");
}

此外,由于此代码在 Amazon EC2 上 运行,我必须向这些用户提供文件夹和文件的完全控制权 -

IUSR
MyProjectName

如果您使用默认的 Internet 信息系统,则默认文件夹 wwwroot 通过您的 Application Pool 直接锁定给指定用户。在大多数情况下,这将是一个 网络服务帐户

您的特定应用程序将具有一定程度的权限,但默认情况下您的网络应用程序不应访问 wwwroot 的其他内容。

目录为:

inetpub - wwwroot - Example
inetpub - wwwroot - Demo

所以 ExampleDemo 都是两个独立的托管网站。因此,如果您尝试从一个应用程序导航到另一个目录,它应该会自动保护您。

但是,如果您需要阻止特定用户或应用程序访问某个网站,这确实是可能的。在目前的状态下,这个问题太宽泛了。

  • 请求过滤
  • URL重写

这是两种方法,但是如果您使用虚拟目录,您应该查看以下内容here

没有虚拟目录,我的上述保护是正确的:

A site is a container for applications and virtual directories, and you can access it through one or more unique bindings.

The binding includes two attributes important for communication: the binding protocol and the binding information. The binding protocol defines the protocol over which communication between the server and client occurs. The binding information defines the information that is used to access the site. For example, the binding protocol of a Web site can be either HTTP or HTTPS, and the binding information is the combination of IP address, port, and optional host header.

我假设您在尝试写入相关文件时冒充调用者。否则,如果您 运行ning 作为系统帐户,写入权限似乎不会受到影响。

因此,除了上面提到的配置(https://serverfault.com/questions/37762/block-access-to-subdirectory-using-web-config)之外,我建议运行通过暂时取消模拟来将文件写入系统帐户的代码块:

using (System.Security.Principal.WindowsImpersonationContext wic = 
     System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero))
{
    FileStream file = new FileStream(Server.MapPath("~/SiteFolder/example.txt"), FileMode.Append, FileAccess.Write, FileShare.Write);
    using (StreamWriter fileWriter = new StreamWriter(file))
    {
         fileWriter.WriteLine("Something");
    }
}