【问题标题】:How to add CDN to bundle.config in asp.net webforms bundling如何在 asp.net webforms 捆绑中将 CDN 添加到 bundle.config
【发布时间】:2013-03-18 06:06:54
【问题描述】:

我正在使用 asp.net 捆绑/缩小并将所有内容放在 bundle.config 中,如下所示:

<styleBundle path="~/css/css">
  <include path="~/css/bootstrap.css" />
  <include path="~/css/flexslider.css" />
  <include path="~/css/font-awesome.css" />
  <include path="~/css/Site.css" />
  <include path="~/css/orange.css" />
</styleBundle>

但我想使用 CDN 中的 bootstrap.css:

//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css

那么我们如何在 bundle.config 中做到这一点呢?

【问题讨论】:

    标签: asp.net bundling-and-minification asp.net-optimization


    【解决方案1】:

    目前,您无法混合和匹配以及从外部来源(如 cdn)提取捆绑包中的某些文件。您可以将整个包上传到 CDN 并配置帮助程序以在 CDN 中呈现对包的引用,但您不能包含来自外部源的文件,这些文件必须位于您的应用可以找到的位置。

    您可以通过实现一个能够在运行时从您的 CDN 获取文件的 VirtualPathProvider 来解决此问题,但您必须自己构建它。

    【讨论】:

      【解决方案2】:

      ASP.NET 文档或许能帮到你 - http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification,有一节叫做使用 CDN

      【讨论】:

      • 这与使用 bundle.config 无关
      【解决方案3】:

      您不能混合捆绑包,但可以在 boundle 配置中包含外部源。

      这里是从here 中挑选的一个示例,正如 randomidea 指出的那样。

      public static void RegisterBundles(BundleCollection bundles)
      {
          //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
          //            "~/Scripts/jquery-{version}.js"));
      
          bundles.UseCdn = true;   //enable CDN support
      
          //add link to jquery on the CDN
          var jqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";
      
          bundles.Add(new ScriptBundle("~/bundles/jquery",
                  jqueryCdnPath).Include(
                  "~/Scripts/jquery-{version}.js"));
      
      // Code removed for clarity.
      }
      

      我们需要启用 CDN,为此我们将 UseCdn 设置为 true,并在 ScriptBundle 构造函数中添加 url。包含文件将在调试模式下使用。

      正如文章所建议的,我们需要有一个备用机制以防我们的 CDN 失败:

          @Scripts.Render("~/bundles/jquery")
      
          <script type="text/javascript">
              if (typeof jQuery == 'undefined') {
                  var e = document.createElement('script');
                  e.src = '@Url.Content("~/Scripts/jquery-1.7.1.js")';
                  e.type = 'text/javascript';
                  document.getElementsByTagName("head")[0].appendChild(e);
      
              }
          </script> 
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2012-11-23
        • 2015-08-11
        • 2012-08-09
        • 2018-08-31
        • 1970-01-01
        • 2012-11-02
        • 2017-09-20
        • 2013-05-26
        • 2016-05-28
        相关资源
        最近更新 更多