ead*_*dam 10 asp.net-core-mvc asp.net-core
我正在使用包Microsoft.AspNet.StaticFiles
并将其配置Startup.cs
为app.UseStaticFiles()
.如何更改已传送文件的标题?我想为图像,css和js设置缓存到期等.
Jos*_*uch 18
您可以使用StaticFileOptions,它包含在静态文件的每个请求上调用的事件处理程序.
你的Startup.cs应该是这样的:
// Add static files to the request pipeline.
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = (context) =>
{
// Disable caching of all static files.
context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store";
context.Context.Response.Headers["Pragma"] = "no-cache";
context.Context.Response.Headers["Expires"] = "-1";
}
});
Run Code Online (Sandbox Code Playgroud)
当然,您可以修改上面的代码来检查内容类型,只修改JS或CSS或任何您想要的标题.
根据上面 Josh Mouch 的回答,添加了代码来确定它是否是 pdf 文件
启动.cs:
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
if(ctx.File.Name.ToLower().EndsWith(".pdf"))
{
ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=86400");
}
else
{
ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=31104000");
}
}
});
Run Code Online (Sandbox Code Playgroud)
如果您正在寻找一种解决方案,允许您为每个环境(开发、生产等)配置不同的行为,这也是在 web.config 文件中设置这些设置而不是对整个内容进行硬编码的要点,那么您可以可以考虑以下方法。
在appsettings.json文件中添加以下键/值部分:
"StaticFiles": {
"Headers": {
"Cache-Control": "no-cache, no-store",
"Pragma": "no-cache",
"Expires": "-1"
}
}
Run Code Online (Sandbox Code Playgroud)
然后在Startup.cs文件的方法中相应添加以下内容Configure
:
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = (context) =>
{
// Disable caching for all static files.
context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
context.Context.Response.Headers["Pragma"] = Configuration["StaticFiles:Headers:Pragma"];
context.Context.Response.Headers["Expires"] = Configuration["StaticFiles:Headers:Expires"];
}
});
Run Code Online (Sandbox Code Playgroud)
appsettings.json
这将允许开发人员使用不同/多个/级联设置文件(appsettings.production.json
等等)定义不同的缓存设置- 这可以使用旧web.config
配置模式来完成 - 使用 ASP.NET Core 的新配置模式。
有关该主题的更多信息,我还建议阅读我的博客上的这篇文章和/或官方 ASP.NET Core 文档中的这些精彩文章:
归档时间: |
|
查看次数: |
4758 次 |
最近记录: |