【问题标题】:In Blazor WebAssembly, how to include hash in static file link/script reference in index.html for cache-busting?在 Blazor WebAssembly 中,如何在 index.html 中的静态文件链接/脚本引用中包含哈希以进行缓存清除?
【发布时间】:2020-08-27 18:33:03
【问题描述】:

在服务器端 ASP.NET 中,我们可以对 .cshtml 文件中的静态资产执行 asp-append-version=true 以自动将文件的哈希附加到文件名。但是,在 Blazor WebAssembly 中,这不起作用,这是有道理的,因为我有一个简单的 index.html 文件,它引导 Blazor 并引用静态文件,而不是服务器修改的文件。

那么在 Blazor WebAssembly 的 index.html 文件中是否有一种将哈希附加到静态文件的 URL 的好方法,其结果类似于旧的 asp-append-version=true?比如让<link href="css/site.css" rel="stylesheet" />变成<link href="css/site.css?v=1234abc..." rel="stylesheet" />,这样在部署时对site.css的修改会导致所有客户端都获取到新修改的静态文件,而不是依赖缓存?

【问题讨论】:

  • 您是否考虑将 index.html 替换为服务器上的 .cshtml 页面?
  • 我认为可能有一种仅限客户端的方式,但我想我可以在必要时这样做。
  • 我不知道 ASP.Net Core 的其他方式。这不能在客户端完成。
  • @PatrickSzalapski 您可以在哪里尝试 .cshtml 方法?成功了吗?
  • 参见docs.microsoft.com/en-us/aspnet/core/blazor/host-and-deploy/… 以及更改dll文件的文件扩展名部分。愚蠢的是,此功能无法开箱即用,因为它是 Web 编程中的最佳实践。

标签: asp.net-core blazor blazor-client-side


【解决方案1】:

我想出了一个解决方法。我创建了一个控制器来处理请求,读取 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 文件中,使用如下网址:

<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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-21
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 2014-07-25
    相关资源
    最近更新 更多