views:

63

answers:

2

I have this ASP.NET MVC application that I now want to separate out the image links to a CDN. At this moment, images typically have this markup code:

<%= Html.ActionLinkWithImage("/Content/Img/Image1.png" ...

This works fine in development using the local web server (Cassini), and also when published the prod server.
But now I want the production URL to something like:

http://cdn.com/Img/Image1.png

How do I get this to work in an easy way, so that it works seamlessly in dev and after published to prod?

+2  A: 

You can create a URL extension method that will, depending on a value from the Web.config file (or something else), generate the debug URL or the live URL.

public static MvcHtmlString CDNImageLink(this UrlHelper url, string imageName)
{
    string urlFormat;
    if((bool)ConfigurationManager.AppSettings["Debug"])
        urlFormat = "/Content/Img/{0}";
    else
        urlFormat = "http://cdn.com/Img/{0}";

    return MvcHtmlString.Create(string.Format(urlFormat, imageName));
}

You can then use this extension method anywhere you need an image url (including Html extension methods):

public static MvcHtmlString ActionLinkWithImage(this HtmlHelper html, string imageName)
{
     UrlHelper Url = new UrlHelper(html.ViewContext.RequestContext);
     string imageUrl = Url.CDNImageLink(imageName);
     // generate the rest of the ActionLink using the imageUrl
}

Make sure you have the using statement for the namespace where the Url extension method is located at the top of the file where you declared the HTML extension method, otherwise it will not recognize it.

Baddie
Great, I also did a similar extension method for standard HTML links: http://insomniacgeek.com/code/how-to-use-cdn-links-in-your-asp-net-mvc-application-to-serve-static-content-from-a-cookieless-domain-using-iis/
Magnus Johansson
A: 

You can also modify your host file to redirect your cdn domain to another IP address. I use this to redirect static.myresources.com to localhost all the time and it keeps your html pretty clean.

jfar