Click here to Skip to main content
15,921,606 members
Articles / Web Development / ASP.NET

Working with a CDN in Development

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
10 Dec 2012CPOL5 min read 32.3K   14   1
Chapter excerpt from Fast ASP.NET Websites
Image 1Fast ASP.NET Websites

By Dean Alan Hume

Content Delivery Networks (CDNs) are becoming more and more affordable and freely available to the public. You will find that many of the top performing websites all use domain sharding to provide a faster platform for their static content. If we combine the power of a CDN’s geographical node base with the browser’s ability to download more efficiently from multiple domains, you will find that your website will drastically improve its load times. The ability to serve your users content from a geographical location that is closer to them also means that latency is reduced and this can be a significant step toward improving the speed of your website. This improvement will be observed across all browsers both old and new. This article, based on chapter 9 of Fast ASP.NET Websites, looks at working with a CDN in development. This article covers the use of an ASP.NET MVC HTML helper, but the full chapter will cover examples in MVC.

You may also be interested in…

The goal of a Content Delivery Network (CDN) is to serve content from a server that is located geographically closer to your users. It’s a shorter distance to travel, and this means quicker response times. A CDN essentially is a collection of server nodes located around the world that contain a clone of static files.

The benefits of using a CDN extend far beyond just brilliant response times, using a CDN also reduces the amount of bandwidth and requests that are served from your website. You will still get all the benefits of caching, compression and a wider network for your website. Because your website will have static content served from such a wide network, it means that the load will be extremely well balanced across your users around the world. Say, for example, you were about to launch a new product online and expect high volumes of traffic, this large distributed network of nodes is much better equipped to handle instantaneous high load.

Suppose you’ve built an app called Surf Store, and you run it against the Yahoo! YSlow web performance tool. Imagine that the performance score for the site currently comes in at 91 out of 100. This is a good score, but, unfortunately, you still score an "F" for a Content Delivery Network. I reckon you could do better! Figure 1 shows the result that the Yahoo! YSlow tool produces.

Image 2

Figure 1 The Yahoo! YSlow score for the sample Surf Store application still needs some improvement.

Adding your website components to a CDN is an easy transition. However, depending on your development environment, it may not always be that advisable to work directly off a CDN while your website is still under development. You may have a development team that constantly needs to access these files and this can end up adding to your bandwidth bills. I often find that it is best to work off local copies while in development and, then, switch to the CDN once the website is in production. I am going to show you a technique in ASP.NET MVC that will allow you to easily work with a CDN while still in development.


We can easily add a HTML helper to our sample application that contains a switch between our development content and the production content on a CDN. Whether you work in a team or not, it can still be beneficial to use development content before moving to production content when your site goes live. The key to using this technique is matching the local file structure to that of your CDN. This makes it easier to navigate between folders and also allows us to easily map to certain files. Let’s run through an example that makes use of this technique.

Begin by adding a key to the Web.config file with the location of the CDN.

Listing 1 Adding the CDN URL to the Web.config

<!— The URL of the CDN ->
<add key="CDNUrl" value=""/>			

In listing 1, we simply add the URL of the Content Delivery Network to the appSettings section of the Web.config file. Next, we are going to use this CDN URL to build up a path for our content depending on whether we are in release mode or debug mode. Begin by adding a new class file to the solution—I named it CdnUtils. Figure 2 shows the newly created class file in the Solution Explorer of the sample application.

Image 3

Figure 2 A new class file is added to the SurfStoreApp MVC project

Inside this new class, add the code in listing 2.

Listing 2 Using the URL of the CDN in debug/release mode

/// <summary>
/// This extension method is used to generate a URL path
/// for the CDN depending on whether or not we are in release mode.
/// </summary>
/// <param name="helper">The MVC HTML helper that is being used.</param>
/// <param name="contentPath">The path of the content. Normally starts with a ~</param>
/// <returns>Returns a full URL based on whether or not in release mode</returns>
public static string CdnUrl(this HtmlHelper helper, string contentPath)
    // Check if we are in release mode. If not, then simply return as normal
    #if (!DEBUG)								

// The content path will often get passed in with a leading ‘~’ sign. We need to remove it // if we append the URL of the CDN to it.
    if (contentPath.StartsWith("~"))					
        contentPath = contentPath.Substring(1);

    // Retrieve the URL of the CDN from the Web.config
    string appSetting = ConfigurationManager.AppSettings["CDNUrl"];	

    // Combine the two URLs and update the content
    Uri combinedUri = new Uri(new Uri(appSetting), contentPath);
contentPath = combinedUri.ToString();					

    // Create the correct URL
    var url = new UrlHelper(helper.ViewContext.RequestContext);

    // Return the new and updated content path
    return url.Content(contentPath);					

The code in listing 2 uses the content path that is passed in and simply updates it with the URL of the CDN depending on whether or not the code is in release mode. If we are still in debug mode, the code will run as normal and simply return the content path that was passed in. Only if we are in release mode will the URL of the CDN get appended to the content path.

Finally, we need to update our views to use the new HTML helper method that we wrote. Instead of calling an HTML image tag like so:

<img src="@Url.Content("~/Content/Images/surfing-homepage.png />

We now use:

<img src="@Html.CdnUrl("~/Content/Images/surfing-homepage.png" />

And this will produce the following HTML when the web page is rendered:

<img src="" />

This simple change ensures that, while you are still developing locally, you aren’t using the bandwidth of your CDN and racking up a hefty bill!


Every time you open up a webpage, you are often making a round trip to a server halfway around the world to retrieve the components required to load the page. These round trips take time and, not surprisingly, the further away that you are from the hosting server, the longer it will take you to download the components of a webpage. The ability to improve this delay comes in the form of a Content Delivery Network. We implemented a technique in the sample Surf Store application that allowed us to easily switch between the content on a CDN and the local content while in development. This technique will speed up your website and hopefully save you some money on your CDN bandwidth bills!

Here are some other Manning titles you might be interested in:

Image 4

ASP.NET MVC 4 in Action
Jeffrey Palermo, Jimmy Bogard, Eric Hexter, Matthew Hinze, and Jeremy Skinner

Image 5

HTML5 for .NET Developers
Jim Jackson II and Ian Gilman

Image 6

Dependency Injection in .NET
Mark Seeman


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

QuestionWebforms solution Pin
IgorDR19-Dec-15 6:22
professionalIgorDR19-Dec-15 6:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.