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

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

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 文件以避免在发布时复制它们。

例如:

<ItemGroup>
	<Content Update="wwwroot/**/*.md">
		<CopyToPublishDirectory>Never</CopyToPublishDirectory>
	</Content>
</ItemGroup>

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

英文:

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

For example:

&lt;ItemGroup&gt;
	&lt;Content Update=&quot;wwwroot/**/*.md&quot;&gt;
		&lt;CopyToPublishDirectory&gt;Never&lt;/CopyToPublishDirectory&gt;
	&lt;/Content&gt;
&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:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = r =>
    {
        // criteria for whatever files you want to be private
        if (r.File.Name.EndsWith("md"))
        {
            r.Context.Response.StatusCode = 404;
            r.Context.Response.ContentLength = 0;
            r.Context.Response.Body = Stream.Null;
        }
    }
});

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:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet(&quot;/&quot;, () =&gt; &quot;Hello World!&quot;);

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = r =&gt;
    {
        // criteria for whatever files you want to be private
        if (r.File.Name.EndsWith(&quot;md&quot;))
        {
            r.Context.Response.StatusCode = 404;
            r.Context.Response.ContentLength = 0;
            r.Context.Response.Body = Stream.Null;
        }
    }
});

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:

确定