You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core中禁止/wwwroot目录下特定文件被访问?

阻止ASP.NET Core中/wwwroot私有文件被客户端访问的方法

完全可以阻止这些私有文件被客户端访问,下面是几种实用的实现方式:

方法一:通过StaticFileOptions配置访问规则

在Program.cs中配置静态文件中间件时,利用OnPrepareResponse回调检查请求的文件路径,对特定文件或目录返回禁止访问的状态码:

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        // 禁止所有.md文件被访问
        if (ctx.File.Name.EndsWith(".md", StringComparison.OrdinalIgnoreCase))
        {
            ctx.Context.Response.StatusCode = StatusCodes.Status403Forbidden;
            ctx.Context.Response.ContentLength = 0;
            ctx.Context.Response.Body = Stream.Null;
        }
        // 禁止访问/wwwroot/internal-docs目录下的所有文件
        else if (ctx.File.PhysicalPath.IndexOf(Path.Combine("wwwroot", "internal-docs"), StringComparison.OrdinalIgnoreCase) >= 0)
        {
            ctx.Context.Response.StatusCode = StatusCodes.Status403Forbidden;
            ctx.Context.Response.ContentLength = 0;
            ctx.Context.Response.Body = Stream.Null;
        }
    }
});

方法二:通过IIS的web.config添加重写规则

如果你的应用部署在IIS上,可以在项目根目录的web.config中添加URL重写规则,直接拦截对特定文件或目录的请求:

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="拦截Markdown文件" stopProcessing="true">
          <match url="^.*\.md$" />
          <action type="CustomResponse" statusCode="403" statusReason="禁止访问" statusDescription="该文件不允许客户端访问" />
        </rule>
        <rule name="拦截内部文档目录" stopProcessing="true">
          <match url="^internal-docs/.*$" />
          <action type="CustomResponse" statusCode="403" statusReason="禁止访问" statusDescription="该目录不允许客户端访问" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

备选方案:将私有文件移到wwwroot外

如果允许调整文件存放位置,把这类内部文件放到/wwwroot目录之外会更安全——ASP.NET Core默认不会对外提供wwwroot以外的静态文件,不过你需要自己处理内部程序对这些文件的访问逻辑。

内容的提问来源于stack exchange,提问作者lonix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 01:40:09