Wednesday, March 16, 2016

Integrating Azure CDN into an ASP.Net MVC application

Using a CDN has a multitude of advantages. I won't go into details about them here. You can Google around for more info ;-)

In the examples one can find online on how to integrate a CDN into an MS MVC application, we see typical examples using the CDN of common libraries like jQuery:

See "Using a CDN" at http://www.asp.net/mvc/overview/performance/bundling-and-minification

It's plain and simple:
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"));
But what if you want to use your own scripts through a CDN like Azure? This works nicely (in BundleConfig):
bundles.Add(new ScriptBundle("~/bundles/jquery", CdnRoot + "/bundles/jquery")
                .Include("~/Content/Scripts/Lib/jquery-{version}.js"));
where CdnRoot is the path to the CDN endpoint, like: //my-endpoint.azureedge.net

This way, the CDN will load the resources from the bundle like in a normal case, store it in its cache, and return it the next times a user requests them. No need to upload the files to the CDN, and changes to the code behind the bundle is taken into account automatically.