英文:
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:
<ItemGroup>
<Content Update="wwwroot/**/*.md">
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</Content>
</ItemGroup>
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("/", () => "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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论