用于获取清除缓存的“版本字符串”的服务/扩展

Cal*_*alC 5 c# offline-caching asp.net-core-mvc asp.net-core asp.net-core-2.0

背景

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

CACHE MANIFEST

CACHE:
/site.min.css
/site.min.js
Run Code Online (Sandbox Code Playgroud)

为了使脱机应用程序正常运行,缓存的文件必须与应用程序中脱机页面请求的文件完全匹配。但是,我想对此清单中引用的js / css资源应用“缓存清除”版本字符串。对于HTML标记,它受的支持,ScriptTagHelper但是我没有找到任何支持纯URL的帮助程序/扩展方法(如上述清单中所要求)。

关于此帖子,我已经通过将a FileVersionProvider注入清单视图并使用以下AddFileVersionToPath()方法来解决了此问题:

CACHE MANIFEST

CACHE:
/site.min.css
/site.min.js
Run Code Online (Sandbox Code Playgroud)

但是,FileVersionProvider该类位于Microsoft.AspNetCore.Mvc.TagHelpers.Internal命名空间中,从维护的角度来看,该命名空间不足以使我充满信心。

最后,我为此实现的DI设置的实现并不完全理想(请参见下文)。我不喜欢这样的事实,我需要打电话给GetService()我并且一定要指定一个特定的MemoryCache

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

是否有人以前曾要求使用版本字符串创建到js / css资源的链接?如果是这样,是否有更优雅的解决方案?

Lio*_*ion 1

您尝试过这种扩展方法吗?它在 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>
Run Code Online (Sandbox Code Playgroud)

生成的 HTML

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

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

FileVersionProvider如果将from的第一个参数替换为hostingEnvironment.WebRootFileProviderto ,则可以更改hostingEnvironment.ContentRootFileProvider。但我还没有测试过它的副作用和安全问题,因此wwwroot如果可能的话,您应该继续使用,因为该文件夹被设计为可供公众访问。