How to use CDN links in your ASP.NET MVC application to serve static content from a cookieless domain

Here’s one way you can use CDN links in your ASP.NET MVC application.

Problem: When you develop your ASP.NET MVC application and use a link to a static content, such as css, jpg’s etc, you may want to server these from a CDN or at least a domain that doesn’t server cookies with the request. For those of you who have been using the Google Page Speed add-in for FireFox, you know what I’m talking about:


So the question is, how do you get your markup that normally may look something like this:

to look something like this on your production server:

When you are developing using the local web server (Cassini), you don’t want the CDN links in your code, but after you have published the page to prod, you want it to use the CDN link. One way to make this work is to make an extension helper method that creates the correct link based on if you run in dev or prod. Here is my suggestion:

public static MvcHtmlString CDNLink(this HtmlHelper html, string tagName, string contentTag, string contentUrl, object htmlAttributes)
  var contentLink = new TagBuilder(tagName);
  var contentServerUrl = ConfigurationManager.AppSettings["ContentServerUrl"];
  contentServerUrl = string.IsNullOrEmpty(contentServerUrl) ? "{0}" : contentServerUrl;
  contentLink.MergeAttribute(contentTag, string.Format(contentServerUrl, contentUrl));
  contentLink.MergeAttributes((IDictionary<string, string="">)htmlAttributes, true);
  return MvcHtmlString.Create(contentLink.ToString());

It is pretty straightforward to use:

<%=html.cdnlink("link", new="" string=""> { {"rel", "stylesheet"},
{"type","text/css"} }) %> <%=html.cdnlink("link", new="" string="">
<%=html.cdnlink("link", new="" string="">

Pass the tag name (“link”), the content attribute (“href”), the actual content link (“file.css”) and optional HTML attributes. In your web.config file, add an application settings for the content server url like this in dev

And in prod, use something like this:

There you go, hope you will find it useful.

This post is licensed under CC BY 4.0 by the author.