不要在ASP.NET Core中为/wwwroot目录提供特定文件。

huangapple go评论100阅读模式
英文:

Do not serve specific files in /wwwroot with ASP.NET Core

问题

你可以阻止它们被提供给客户端吗?

英文:

Sometimes I have non-image/js/css files in /wwwroot, for internal purposes. For example, maybe I have a README.md in some subdirectory, documenting something about that location; that would be the natural place for it.

But in an ASP.NET Core app, everything in /wwwroot is served to the client, including those private files.

Can I prevent them being served?

答案1

得分: 3

一种选择是配置您的 csproj 文件以避免在发布时复制它们。

例如:

  1. <ItemGroup>
  2. <Content Update="wwwroot/**/*.md">
  3. <CopyToPublishDirectory>Never</CopyToPublishDirectory>
  4. </Content>
  5. </ItemGroup>

另一种选择是使用构建后事件来删除文件。

英文:

One option is to configure your csproj file to avoid copying them on publish.

For example:

  1. &lt;ItemGroup&gt;
  2. &lt;Content Update=&quot;wwwroot/**/*.md&quot;&gt;
  3. &lt;CopyToPublishDirectory&gt;Never&lt;/CopyToPublishDirectory&gt;
  4. &lt;/Content&gt;
  5. &lt;/ItemGroup&gt;

Another option would be to use post-build events to delete the files

答案2

得分: 3

以下是翻译好的部分:

"Kind of a hack, but if you're serving the files with UseStaticFiles, you could use the OnPrepareResponse callback to do something like this:

  1. var builder = WebApplication.CreateBuilder(args);
  2. var app = builder.Build();
  3. app.MapGet("/", () => "Hello World!");
  4. app.UseStaticFiles(new StaticFileOptions
  5. {
  6. OnPrepareResponse = r =>
  7. {
  8. // criteria for whatever files you want to be private
  9. if (r.File.Name.EndsWith("md"))
  10. {
  11. r.Context.Response.StatusCode = 404;
  12. r.Context.Response.ContentLength = 0;
  13. r.Context.Response.Body = Stream.Null;
  14. }
  15. }
  16. });
  17. app.Run();

Credit: I referred to this post for some details, such as resetting ContentLength and the Body stream."

英文:

Kind of a hack, but if you're serving the files with UseStaticFiles, you could use the OnPrepareResponse callback to do something like this:

  1. var builder = WebApplication.CreateBuilder(args);
  2. var app = builder.Build();
  3. app.MapGet(&quot;/&quot;, () =&gt; &quot;Hello World!&quot;);
  4. app.UseStaticFiles(new StaticFileOptions
  5. {
  6. OnPrepareResponse = r =&gt;
  7. {
  8. // criteria for whatever files you want to be private
  9. if (r.File.Name.EndsWith(&quot;md&quot;))
  10. {
  11. r.Context.Response.StatusCode = 404;
  12. r.Context.Response.ContentLength = 0;
  13. r.Context.Response.Body = Stream.Null;
  14. }
  15. }
  16. });
  17. app.Run();

Credit: I referred to this post for some details, such as resetting ContentLength and the Body stream.

huangapple
  • 本文由 发表于 2023年5月7日 21:34:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定