Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to switch between static assets and CDN based assets for development and deployment

I am developing and application in ASP.NET MVC3. I am planning to take advantage of Amazons Cloudfront offering as a CDN to serve static assets.

I am curious if anyone has devised a simple method for switching between local assets for development and CDN based assets for deployment?

Any tips or tricks would be greatly appreciated.

like image 709
stephen776 Avatar asked Feb 20 '12 17:02

stephen776


2 Answers

Similarly to Paul's answer.

In the past I've used an extension method for UrlHelper that created the links based on a value from the web.config.

This is helpful so you don't have to minipulate your views after publishing, and it's as simple as updating a web.config entry on publish. Any resources that require using the CDN resource, you simply say Url.CdnContent("~/site.css")

I'm not on my development pc at the moment, but when I get home, I'll get you the source for my extension method

It's very simplistic, but it works for what I need it to do

public static string CdnContent(this UrlHelper helper, string relativePath)
{
    var cdnRoot = ConfigurationManager.AppSettings["cygnus.cdnroot"];
    if (string.IsNullOrEmpty(cdnRoot))
        return UrlHelper.GenerateContentUrl(relativePath, helper.RequestContext.HttpContext);

    if (relativePath.StartsWith("~"))
        relativePath = relativePath.Substring(1);

    if (cdnRoot.EndsWith("/"))
        cdnRoot = cdnRoot.Substring(0, cdnRoot.Length - 1);

    if (!relativePath.StartsWith("/"))
        relativePath = "/" + relativePath;

    return cdnRoot + relativePath;
}
like image 173
Anthony Shaw Avatar answered Nov 15 '22 08:11

Anthony Shaw


I've done it in the past using a few simple rules:

  • Always use file relative paths in CSS
  • Always use a standard pattern to reference content in your views (I use application relative paths with Url.Content, ie. Url.Content("~/content/file.jpg"))
  • Do not reference files in JavaScript.

Then in my deploy process I can simply copy all static assets from the site to the CDN, the CSS will just work since its relative (CSS url() values are always relative to the CSS file they are in, not the request), and I will use regex to replace any strings in my views that are in the form I expect to have the CDN base path.

like image 41
Paul Tyng Avatar answered Nov 15 '22 07:11

Paul Tyng