CDN in ASP.NET MVC bundling

Once you create ASP.NET MVC project and you looked into the App_start folder BundleConfig.cs file you will fine following code for jQuery bundle.

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
        "~/Scripts/jquery-{version}.js"));

Here you can see that there is a ScriptBundle object created with new. This ScriptBundle object also contains another constructor which also take path of cdn as parameter.

Now let’s first run application without adding CDN and see how its works.

bundle-without-cdn-asp-net-mvc

You can see its loaded from bundle not using any CDN there. So Let’s see how we are going to use CDN there. There are lots of CDNs are available there but I’m going to use Microsoft Hosted CDN file in our sample application.

You can find all CDN hosted file on following location.

http://www.asp.net/ajaxlibrary/cdn.ashx

and here all the jQuery CDN listing for all the versions.

http://www.asp.net/ajaxlibrary/cdn.ashx#jQuery_Releases_on_the_CDN_0

I’m going to use jQuery 1.10.2 version as ASP.NET MVC application by default comes with that version only. Following is a code for that.

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

Here you can see that I have used path without http so that whether you use https or http it will work on both side. Also you can see that I have enabled UseCdn proper to true that will tell bundle to use CDN whenever its available.

As CDN is used in release version, to test application we need to set Debug=”False” in our web.config check that in local machine. So once you are done with that and run in browser you can see in below image its using CDN instead of local file.

cdn-for-bundling-asp-net-mvc-browser-demo