Asp.net-Mvc

ASP 包中的絕對 URL

  • April 17, 2015

我為Google地圖使用了一個 jQuery 庫,它依賴於首先載入的Google腳本。我希望能夠將兩者都包含在捆綁包中:

 bundles.Add(new ScriptBundle("myfoobundle").Include(
   "http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places",
   "~/scripts/jquery.fooplugin-{version}.js"
 ));

這似乎不起作用(引發抱怨第一個字元串的異常)。有人可能會說這不應該工作,因為絕對 URL 並不意味著被縮小/捆綁。

但是目前的方法很麻煩,因為我需要確保依賴關係是正確的,並且這種情況發生在不同的地方(捆綁程式碼中的一半問題,視圖中的另一半)。

有一個如上所述的 1 步解決方案會很好。在這方面我有什麼選擇嗎?

更新:

解決有關使用 CDN 作為解決方案的評論:如果我指定bundles.UseCdn = true它無效,我仍然會收到異常The URL 'http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places' is not valid. Only application relative URLs (~/url) are allowed。另外我不確定這樣做的意義是什麼,因為我已經使用了對 jQuery 等的 CDN 支持,所以不確定這會如何與我的案例發生衝突。

目前,您必須在捆綁包中包含您所依賴的 jquery 的本地副本,或者您必須管理您提到的腳本標籤。我們知道這種依賴管理問題,它屬於資產管理類別,我們正在使用codeplex 上的此工作項進行跟踪

如果您使用System.Web.Optimization>= 1.1.2 的版本,則有一種新的便捷方法可以覆蓋 url 的 forStylesScripts。在下面的範例中,我獲取了一個CdnBaseUrlfromweb.config以用作所有腳本和样式表的基本 url:

public class BundleConfig
{
   private static readonly string BaseUrl = ConfigurationManager.AppSettings["CdnBaseUrl"];

   public static void RegisterBundles(BundleCollection bundles)
   {
       // This is the new hotness!!
       Styles.DefaultTagFormat = "<link href=\"" + BaseUrl + "{0}\" rel=\"stylesheet\"/>";
       Scripts.DefaultTagFormat = "<script src=\"" + BaseUrl + "{0}\"></script>";

       bundles.Add(new ScriptBundle("~/bundles/js").Include(
           "Your scripts here..."
       ));

       bundles.Add(new StyleBundle("~/bundles/css").Include(
           "Your css files here..."
       ));
   }
}

有關靜態站點 (CDN) 優化的更多資訊

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