带有CDN的ASP.NET MVC多虚拟路径捆绑包

本文关键字:路径 虚拟 MVC CDN ASP NET 带有 | 更新日期: 2023-09-27 17:59:52

我正在尝试添加一些具有CDN功能的ASP.NET MVC 4捆绑包。其目的是由托管在同一数据中心中的许多其他站点在本地共享内容

第一次尝试是:

            bundles.Add(new ScriptBundle("~/bundles/jquery", "http://mysite/Content/js/").Include(
                                                              "http://mycdnsite/Content/js/jquery.unobtrusive-ajax.min.js",
                                                              "http://mycdnsite/Content/js/jquery-migrate-1.2.1.js",
                                                              "http://mycdnsite/Content/js/jquery-{version}.js"));

不幸的是,这是不可能的,因为virtualPaths必须是相对的(只允许应用程序相关url(~/url))

然后我尝试了这个:

        bundles.Add(new ScriptBundle("~/bundles/jquery", "http://mycdnsite/Content/js/").Include(
                                                              "~/jquery.unobtrusive-ajax.min.js",
                                                              "~/jquery-migrate-1.2.1.js",
                                                              "~/jquery-{version}.js"));

但它没有起作用,甚至启用了CDN:

BundleTable.EnableOptimizations = true;
bundles.UseCdn = true;

是否可以使用CDN创建多内容捆绑包?

带有CDN的ASP.NET MVC多虚拟路径捆绑包

AFAIK您不能不在一个捆绑包中为多个CDN主机提供服务。ScriptBundle允许您为捆绑包指定备用URL,并且捆绑包可以包含多个本地文件。你的语法是正确的。

bundles.UseCdn = true;
bundles.Add(new ScriptBundle("~/bundles/jquery",
   @"//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.js"
   ).Include(
    "~/Scripts/jquery-{version}.js"));

有几种方法可以解决这个问题。

  1. 每个CDN托管脚本有一个捆绑包
  2. 手动创建一个文件包,并将它们上传到您自己的CDN并引用
public static void RegisterBundles(BundleCollection bundles)
{
    bundles.UseCdn = true;   // enable CDN     
    // How to add link to jQuery on the CDN ?
    var jqueryCdnPath = "http://mycdnsite/Content/js/jquery.unobtrusive-ajax.min.js";
    bundles.Add(new ScriptBundle("~/bundles/jquery", jqueryCdnPath)
           .Include("~/Scripts/jquery-{version}.js"));
}