asp.net-core - 在 Blazor WebAssembly 中,如何在 index.html 中的静态文件链接/脚本引用中包含哈希以进行缓存清除?
问题描述
在服务器端 ASP.NET 中,我们可以asp-append-version=true
对 .cshtml 文件中的静态资产执行操作,以便自动将文件的哈希附加到文件名中。但是,在 Blazor WebAssembly 中,这不起作用,这是有道理的,因为我有一个简单的 index.html 文件,它引导 Blazor 并引用静态文件,而不是服务器修改的文件。
那么在 Blazor WebAssembly 的 index.html 文件中是否有一种将哈希附加到静态文件的 URL 的好方法,其结果类似于旧的asp-append-version=true
?例如,要 make <link href="css/site.css" rel="stylesheet" />
become <link href="css/site.css?v=1234abc..." rel="stylesheet" />
,因此在部署时对 site.css 的更改将导致所有客户端获取新更改的静态文件,而不是依赖缓存?
解决方案
我想出了一个解决方法。我创建了一个控制器来处理请求,读取 index.html,搜索并替换“{version}”占位符,然后返回内容。
第一步是修改 Startup.cs:
//endpoints.MapFallbackToFile("index.html");
endpoints.MapFallbackToController("Index", "Home");
然后创建一个像这样的控制器:
public class HomeController : Controller
{
private static string _processedIndexFile;
private readonly IWebHostEnvironment _webHostEnvironment;
public HomeController(IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment = webHostEnvironment;
}
[ResponseCache(CacheProfileName = CacheProfileNames.NoCache)]
public IActionResult Index()
{
return ProcessAndReturnIndexFile();
}
private IActionResult ProcessAndReturnIndexFile()
{
if (_processedIndexFile == null)
{
IFileInfo file = _webHostEnvironment.WebRootFileProvider.GetFileInfo("index.html");
_processedIndexFile = System.IO.File.ReadAllText(file.PhysicalPath);
_processedIndexFile = _processedIndexFile.Replace("{version}", AppInfo.CompiledOn.ToString("yyyy'-'MM'-'dd'-'HH'-'mm'-'ss"));
}
return Content(_processedIndexFile, "text/html");
}
}
最后在 index.html 文件中,使用如下 URL:
<link href="css/app.min.css?v={version}" rel="stylesheet" />
这还允许您在返回 Index 方法中的文件之前做一些其他的事情,例如检查返回到 index.html 是否对当前请求是正确的:
// Check for incorrect fallback routes
if (Request.Path.Value?.Contains("api/") == true)
return NotFound();
推荐阅读
- c# - 下拉列表拒绝正确绑定记录
- python - 如何更改分类 x 轴的绘图顺序
- docker - 将前端烧瓶容器连接到后端烧瓶容器
- c++ - 在实践中,是否可以在 API 标头中添加宏以更改类的布局(或大小)?
- java - 为什么@NotBlank 不显示为导入
- python - JSON with Bytes : TypeError: 'abc' 有类型
,但预期其中之一:( ,) - clojure - 在 clojure 中的单个命令中更新多个值
- java - Android Studio 中的动画太慢了
- java - 命令提示符运行中的 Java.lang.NoClassDefFoundError
- javascript - 如何在类中调用函数?