Service/extension 获取缓存破坏 'version string'

Service/extension for getting a cache-busting 'version string'

背景

我有一个应用程序,其中 3 个视图利用 html5 离线应用程序功能。因此,我在剃须刀视图中生成了一个应用程序清单。此视图的简化版本可能如下所示:

CACHE MANIFEST

CACHE:
/site.min.css
/site.min.js

为了使离线应用程序正常运行,缓存文件必须与应用程序内离线页面请求的文件完全匹配。但是,我想将 'cache-busting' 版本字符串应用于此清单中引用的 js/css 资源。对于 HTML 标签,ScriptTagHelper 支持此功能,但我还没有找到任何 helpers/extension 方法支持普通 URL(如上述清单中所要求)。

参考, I have resolved this by injecting a FileVersionProvider进入我的清单视图并使用AddFileVersionToPath()方法如下:

@inject FileVersionProvider versionProvider
CACHE MANIFEST

CACHE:
@versionProvider.AddFileVersionToPath("/site.min.css")
@versionProvider.AddFileVersionToPath("/site.min.js")

但是,FileVersionProvider class 位于 Microsoft.AspNetCore.Mvc.TagHelpers.Internal 命名空间中,从维护的角度来看,这并没有让我充满信心。

最后,我为此实现的 DI 设置并不十分理想(见下文)。我不喜欢需要调用 GetService() 的事实,当然我应该指定特定的 MemoryCache?

services.AddSingleton<FileVersionProvider>(s => 
    new FileVersionProvider(
        s.GetService<IHostingEnvironment>()?.WebRootFileProvider, 
        s.GetService<IMemoryCache>(), 
        new PathString("") ));

问题

有没有人要求用版本字符串创建一个 link 到 js/css 资源?如果可以,有没有更优雅的解决方案?

你试过了吗?它在 ASP.NET Core 2.1 LTS 上对我有用,没有任何依赖注入,只是扩展方法。如果您仍然使用它,也应该在 2.0 中工作。

我有一个类似的用例,其中 SCEditor 从 JavaScript 传递的路径加载 CSS。

@{
    // Without version hash cache buster, the editor internally cache the request and we don't get the new stylesheet - even not with CTRL + F5
    string editorThemePath = this.AddFileVersionToPath("/css/my-editor-theme.css");
}
<script>
      sceditor.create(editorTextarea, {
            // ...
            style: '@editorThemePath'
      })
</script>

生成HTML

<script>
      sceditor.create(editorTextarea, {
            style: '/css/my-editor-theme.css?v=sRU_qBg7xyQElPLskjekOlvSHdRF2Ap1leTP8ui4CaI',
      })
</script>

请记住,此实现需要相对于 wwwroot 的路径。所以在这种情况下,/css/my-editor-theme.csswwwroot/css/my-editor-theme.css 中。

如果将 FileVersionProvider 的第一个参数从 hostingEnvironment.WebRootFileProvider 替换为 hostingEnvironment.ContentRootFileProvider,则可以更改。但我还没有测试过它的副作用和安全问题,所以如果可能的话你应该留在 wwwroot 上,因为这个文件夹被设计为 public 可访问。