Asp.net-Mvc

將記憶體破壞器添加到非優化包?

  • April 6, 2019

我在 MVC 中使用捆綁並具有以下內容:

@Scripts.Render("~/bundles/scripts.js");

BundleTable.EnableOptimizations = true這呈現為:

<script src="/bundles/scripts.js?v=RF3ov56782q9Tc_sMO4vwTzfffl16c6bRblXuygjwWE1"></script>

BundleTable.EnableOptimizations = false這呈現為:

<script src="/js/header.js"></script>
<script src="/js/content.js"></script>
<script src="/js/footer.js"></script>

是否可以攔截非優化版本以包含我自己的自定義記憶體破壞器?

例如:

<script src="/js/header.js?v=12345"></script>
<script src="/js/content.js?v=12345"></script>
<script src="/js/footer.js?v=12345"></script>

為什麼需要?在開發中,BundleTable.EnableOptimizations = false無論如何都沒有記憶體任何東西,而在生產中,您也應該BundleTable.EnableOptimizations = true否定對這樣的東西的需求。

簡短的回答是否定的,沒有內置的東西可以讓你做你想做的事,主要是因為我已經說過的原因:根本不需要這樣的功能。

這是您正在尋找的深入解決方案:

https://volaresystems.com/blog/post/2013/03/18/Combining-JavaScript-bundling-minification-cache-busting-and-easier-debugging

總結一下記憶體破壞部分,創建一個實用方法,它將連接您想要記憶體破壞的非優化文件的文件創建時間戳。

例如

<script src="@StaticFile.Version("/js/header.js")"></script>

這將產生你正在尋找的東西:

<script src="/js/header.js?v=12345"></script>

記憶體清除實用程序方法:

using System.IO;
using System.Web.Caching;
using System.Web.Hosting;

namespace System.Web.Optimization
{
   public static class StaticFile
   {
       public static string Version(string rootRelativePath)
       {
           if (HttpRuntime.Cache[rootRelativePath] == null)
           {
               var absolutePath = HostingEnvironment.MapPath(rootRelativePath);
               var lastChangedDateTime = File.GetLastWriteTime(absolutePath);

               if (rootRelativePath.StartsWith("~"))
               {
                   rootRelativePath = rootRelativePath.Substring(1);
               }

               var versionedUrl = rootRelativePath + "?v=" + lastChangedDateTime.Ticks;

               HttpRuntime.Cache.Insert(rootRelativePath, versionedUrl, new CacheDependency(absolutePath));
           }

           return HttpRuntime.Cache[rootRelativePath] as string;
       }
   }
}

引用自:https://stackoverflow.com/questions/25895158