angular - 在 .Net Core Angular 5 网站中缓存破坏 index.html
问题描述
我正在使用 .Net core 和 angular 5 创建一个网站。我使用最新的 .Net core angular 模板创建了项目(使用dotnet new angular
安装了 .Net core 2.1)。
该项目使用 Angular cli 构建/打包并将哈希应用于捆绑的 js 和 css 文件:
但是,在将我的网站发布到 azure 应用服务后,我发现当我浏览该网站时,我会看到旧版本,直到我使用 F5 手动刷新(不需要 Ctrl-F5)。这似乎是因为虽然 js/css 文件不会被缓存,但包含对这些文件的引用的 index.html 页面将从缓存中提供。
当我按 F5 重新加载网站时,home
从网站请求 index.html(如下)(在这种情况下为 304,因为它没有更改,如果有,它将获得最新的):
但是,当我最初加载页面时(通过书签或输入地址等),页面直接从缓存中提供:
这是预期的行为吗?为什么第一次加载页面与按 F5 不同?我可以/应该阻止这种缓存吗?
解决方案
这是我结合一堆答案后得出的结论。我的目标是永远不缓存 index.html。当我在那里时,由于 Angular 可以很好地缓存js
和css
文件,我让它缓存所有其他资产一年。
只需确保您对在 Angular 之外管理的资产(例如图像)使用缓存清除机制。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
app.UseStaticFiles();
if (env.IsDevelopment())
{
// no caching
app.UseSpaStaticFiles();
}
else
{
app.UseSpaStaticFiles(new StaticFileOptions
{
OnPrepareResponse = context =>
{
context.Context.Response.Headers.Add("Cache-Control", "max-age=31536000");
context.Context.Response.Headers.Add("Expires", "31536000");
}
});
}
// ...
app.UseSpa(spa =>
{
spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions
{
OnPrepareResponse = context =>
{
// never cache index.html
if (context.File.Name == "index.html")
{
context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
context.Context.Response.Headers.Add("Expires", "-1");
}
}
};
});
}
其他 StackOverflow 答案:禁用 .Net Core 中的缓存| 缓存一年
推荐阅读
- javascript - 状态更新但组件不变
- javascript - 如果回调中的语句未正确执行(Javascript)
- date - 我想知道一种将“yyyy-mm-dd”日期类型数据链接到 DataStudio 的有效方法
- android - 不允许在cordova android上加载本地资源
- php - 尝试访问 int 类型值的数组偏移量
- postgresql - 如何使用其 IP 连接到容器化数据库?
- vba - 使用 Selenium Vba 从下拉框中获取数据问题
- javascript - 如何在 Scriptable App 中将 Base64 转换为图像
- android - 为什么当 RoomDao 中的数据发生变化时我的流程没有触发
- c - 矩阵中的垃圾值?