【问题标题】:Use CDN for ASP MVC Bundle with version tag为带有版本标签的 ASP MVC Bundle 使用 CDN
【发布时间】:2014-12-03 16:26:26
【问题描述】:

我想将 CDN 与我的 Bundle 一起使用,但 ASP MVC 不能原生处理 CDN url 的版本。

例如:

public static void RegisterBundles(BundleCollection bundles)
{
    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"));
}

我不能使用{version} 标签在jqueryCdnPath 内,Framewok 无法知道我想要远程 url 中的本地版本。 有没有办法解决这个限制?如何检索本地版本来构建 CDN url?

【问题讨论】:

    标签: asp.net-mvc cdn


    【解决方案1】:

    我有一个选项,但它仅在 virtualPath 中使用 {version} 标记时才有效。一些脚本(bootstrap、globalize...)不需要版本标签,而且我无法知道要在 CDN 上引用的版本号。

    private static string GetLastIncludedVirtualPath(this Bundle bundle)
    {
      var files = bundle.EnumerateFiles(new BundleContext(new HttpContextWrapper(HttpContext.Current), new BundleCollection(), ""));
      var lastFile = files.LastOrDefault();
      if (lastFile == null)
        throw new InvalidOperationException("You must include a file so version can be extracted");
      return lastFile.IncludedVirtualPath;
    }
    
    public static Bundle IncludeWithVersionnedCdn(this Bundle bundle, string virtualPath, string cdnPath, params IItemTransform[] transforms)
    {
      if (bundle == null)
        throw new ArgumentNullException("bundle");
      if (cdnPath == null)
        throw new ArgumentNullException("cdnPath");
      bundle.Include(virtualPath, transforms);
      //GetVersion
      int lengthBeforeVersion = virtualPath.IndexOf("{version}", StringComparison.OrdinalIgnoreCase);
      if (lengthBeforeVersion == -1)
        throw new ArgumentException("Path must contains {version} when version argument is not specified", "virtualPath");
      var includedPath = bundle.GetLastIncludedVirtualPath();
      int lengthAfterVersion = virtualPath.Length - lengthBeforeVersion - "{version}".Length;
      string version = includedPath.Remove(includedPath.Length - lengthAfterVersion).Substring(lengthBeforeVersion);
      //Set CDN
      bundle.CdnPath = cdnPath.Replace("{version}", version);
      return bundle;
    }
    

    用法:

    bundles.Add(new ScriptBundle("~/bundles/jquery")
                    .IncludeWithVersionnedCdn(
                        "~/Scripts/jquery-{version}.js",
                        "//ajax.aspnetcdn.com/ajax/jQuery/jquery-{version}.min.js"));
    

    【讨论】:

      最近更新 更多