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:

Untitled1

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:

 

It is pretty straightforward to use:

<%=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

There you go, hope you will find it useful.