Pat*_*ski 13 asp.net-core blazor blazor-client-side
在服务器端 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 将导致所有客户端 GET 新更改的静态文件,而不是依赖缓存?
我为此想出了一个解决方法。我创建了一个控制器来处理请求、读取index.html、搜索并替换“{version}”占位符,然后返回内容。
第一步是修改 Startup.cs:
//endpoints.MapFallbackToFile("index.html");
endpoints.MapFallbackToController("Index", "Home");
Run Code Online (Sandbox Code Playgroud)
然后创建一个像这样的控制器:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
最后在index.html文件中,使用如下url:
<link href="css/app.min.css?v={version}" rel="stylesheet" />
Run Code Online (Sandbox Code Playgroud)
这还允许您在 Index 方法内返回文件之前执行一些其他操作,例如检查回退到 index.html 对于当前请求是否正确:
// Check for incorrect fallback routes
if (Request.Path.Value?.Contains("api/") == true)
return NotFound();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
862 次 |
| 最近记录: |