Amazon CloudFront CDN and ASP MVC

I needed to use a CDN in my ASP MVC app and needed it to be easy to develop against. I chose Amazon CloudFront since our servers are running on Amazon EC2 and we are also using Amazon S3 during our deployment. You can get a good introduction and step-by-step on CloudFront here.

As for the ASP MVC side, I wanted to have something like Url.Content where it converts my URL to my CDN URL while allowing for multiple development environments.

Here is how I did it:

A helper extension class on System.Web.Mvc.UrlHelper to add a new method to Url: This one is CdnContent

Here is an implementation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Web.Mvc;
using System.Configuration;

namespace CdnHelpers
{
public static class CdnHelpers
{
private static AppEnvironment _appEnvironment = AppEnvironment.Unknown;
private static string _cdnBase = string.Empty;

private static AppEnvironment AppEnvironment
{
get
{
if (_appEnvironment == AppEnvironment.Unknown)
{
_appEnvironment =
(AppEnvironment)
Enum.Parse(typeof (AppEnvironment), ConfigurationManager.AppSettings["App.Environment"], true);
}

return _appEnvironment;
}
}

private static string CdnBase
{
get
{
if (string.IsNullOrEmpty(_cdnBase))
{
_cdnBase = ConfigurationManager.AppSettings["Cdn.Base"];
}

return _cdnBase;
}
}

public static string CdsContent(this System.Web.Mvc.UrlHelper url, string contentPath)
{
if (AppEnvironment == AppEnvironment.Local)
{
return url.Content(contentPath);
}
else
{
contentPath = contentPath.TrimStart('~');

return string.Concat(CdnBase, "/", AppEnvironment.ToString().ToLower(), contentPath);
}
}
}
}

AppEnvironment is an Enum:

    public enum AppEnvironment
    {
        Unknown,

        Local,

        Test,

        Dev,

        Staging,

        Production
    }

You need to add two keys to AppSettings of the Web.config:
App.Environment to determine which environment the code is running as and
Cdn.Base which would be something like http://cache.mydomain.com (no trailing slash)

Also add the namespace of the helper class to System.Web/Pages/Namespaces under Web.config

This should be it. Now you can replace a Url.Content with Url.CdnContent in the code.

I didn’t want to redirect all files by their extension to CDN but that’s not difficult to implement.

On deployment to Amazon:

  • Amazon CDN files and folders are case sensitive.
  • Create folders with the name of your environments under the root of the S3 bucket and deploy the files and folders there.

0 comments ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment