ASP.NET MVC multiple virtualpath Bundle with CDN

2019-05-10 19:10发布

问题:

I´m trying to add some CDN capable bundle with ASP.NET MVC 4. The purpose is to share content locally by many other sites hosted in the same data center

The first attempt was:

            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"));

Unfortunatelly, this is not possible, because the virtualPaths must be relative (Only application relative URLs (~/url) are allowed)

Then I´ve tried this:

        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"));

But it hasn't worked, even enabling CDN:

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

Is it possible to create a multiple content bundle with CDN?

回答1:

AFAIK you can't not serve multiple CDN hosts in one bundle. ScriptBundle allows you to specify an alternate URL for the bundle and the bundle could contain several local files. The syntax you have is correct.

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

There are a couple of ways to solve this problem.

  1. Have one bundle per CDN hosted script.
  2. Manually create a bundle of the files and upload them to your own CDN and reference that.


回答2:

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"));
}