【发布时间】:2016-01-15 12:53:50
【问题描述】:
在以前的版本中,我会像在here 中那样做。但是在新版本的 ASP 中没有 web.config 文件,我认为应该在 launchSettings.json 文件中完成。
基本上我想要做的是停止缓存 app.js 文件和模板文件夹中的所有 .html 文件。我该怎么做?
【问题讨论】:
标签: asp.net caching iis asp.net-core
在以前的版本中,我会像在here 中那样做。但是在新版本的 ASP 中没有 web.config 文件,我认为应该在 launchSettings.json 文件中完成。
基本上我想要做的是停止缓存 app.js 文件和模板文件夹中的所有 .html 文件。我该怎么做?
【问题讨论】:
标签: asp.net caching iis asp.net-core
请注意,您仍然可以在 HTML 页面中为您不想缓存的每个页面添加 <meta> 标签:
<meta http-equiv="cache-control" content="no-cache" />
另外请注意,如果您要部署到 IIS,那么您仍然有一个 wwwroot(或您在 project.json 中指定的内容),您可以在其中放置一个 web.config 文件(由 IIS 解析)。
如果你想通过配置来做,那么在你的 Startup 类中添加一个 Configure() 方法:
public void Configure(IApplicationBuilder application)
{
application.Use(async (context, next) =>
{
context.Response.Headers.Append("Cache-Control", "no-cache");
await next();
});
// ...
}
请注意,如果您只想将该 HTTP 标头应用于某些页面,您只需要检查HttpRequest 的PathString 属性(HttpContext 的Request 属性)或者如果您需要它用于每个静态文件(如果您只想申请其中一些,则与上述相同)使用:
application.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = context =>
{
context.Response.Headers.Append("Cache-Control", "no-cache");
}
};
Making sure a web page is not cached, across all browsers 讨论了您应该发送哪些标头以与您需要支持的浏览器兼容。
【讨论】:
context.Response.Headers.Append("Cache-Control", "private, max-age=0") 而不是context.Response.Headers.Append("Cache-Control", "no-cache");(参见the answer)。它应该适用于所有情况下包含代理。
context.Response.Headers.Append("Cache-Control", "private, no-store") 而不是context.Response.Headers.Append("Cache-Control", "no-cache");
如果您是 .Net Core 中的 PWA 开发人员,或者您是 react 或 angular,您可以使用以下代码缓存除 service worker 或您的主 app.js 之外的所有静态文件。如果对你有帮助,请点赞:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
//One year 31536000
string cachePeriod = env.IsDevelopment() ? "600" : "31536000";
app.UseStaticFiles(new StaticFileOptions{ OnPrepareResponse = ctx => {
if (ctx.File.Name == "sw.js")
{
ctx.Context.Response.Headers.Append("Cache-Control", $"public, no-cache");
}
else
{
ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
}
} });
//...
}
【讨论】: