1.在服务器/客户端应用的wwwroot目录中添加一个名为“service-worker.published.js”的文件,该文件应该是您服务工作者JS的已编译版本。
2.在 startup.cs 文件中添加以下代码,将 Blazor 的策略更改为尝试从 cache 存储中更频繁地获取静态文件:
services.AddResponseCaching();
app.UseResponseCaching();
app.Use(async (context, next) =>
{
context.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue
{
Public = true,
MaxAge = TimeSpan.FromSeconds(60)
};
context.Response.Headers[HeaderNames.Vary] =
new string[] { "Accept-Encoding" };
await next();
if (context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value) &&
!context.Request.Path.Value.StartsWith("/api/"))
{
context.Request.Path = "/index.html";
context.Response.StatusCode = 200;
await next();
}
});
3.在index.html文件中添加以下代码,以使应用程序能够在服务工作者注册时找到相应的文件:
@if (env.IsDevelopment())
{
}
else
{
}
通过以上修改,您的 Blazor 应用程序应该能够在运行时正确加载服务工作者 JS。