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.
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;
}
I've done it in the past using a few simple rules:
Url.Content
, ie. Url.Content("~/content/file.jpg")
)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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With