Question

I'm wondering if there's an easy way to specify a CDN for all content that I reference through Url.Content in my views.

Something that I could configure in my Web.config file in a way similar to the following.

    <cdn>
        <add filetype="css" root="http://mycdn.mydomain.com/stylesheets/" />
        <add filetype="js" root="http://myjscdn.mydomain.com/js/ />
    </cdn>

Then, I could just have <%= Url.Content("~/Content/StyleSheets/What.css") %> and it would output http://mycdn.mydomain.com/stylesheets/Content/StyleSheets/What.css.

If nothing is available, I'll just do it myself via extension methods, but I was wondering if it was possible out of the box.

Was it helpful?

Solution

The answer above is probably correct, here is how it might look in practice:

// @ UrlHelperExtensions.cs

public static class UrlHelperExtensions 
{ 
    public static string CdnContent(this UrlHelper helper, string contentPath)
    {
        return (ConfigurationManager.AppSettings["CDN_Available"] == "True")
              ? ConfigurationManager.AppSettings["CDN_ContentRootUrl"] 
                   + contentPath.TrimStart('~')
              : helper.Content(contentPath);
}

// @ Web.config 

<appSettings>
    // ...
    <add key="CDN_Available" value="True" />
    <add key="CDN_SiteImageRoot" value="http://cdn.gbase.com/images/" />
    // ...
</appSettings>

// @ MyPage.cs

<link href="@Url.CdnContent("~/client/css/mymin.css")" rel="stylesheet" type="text/css" media="all" />

I think that works.. You can also use multiple extension methods to segregate sorts of content to serve locally and those on the CDN.. There is no requirement that the configuration is in web.config though, just useful for development and management.

OTHER TIPS

I don't believe there is anything built in to facilitate this for you. That said, is adding this to Web.config really necessary?

I guess if you don't want to include your CDN-distributed items on every page in your application, I could understand extrapolating the URLs to a central location somewhere, but even then it seems like you could just write some extension methods that return a constant string instead of messing with the Web.config. I know some people cringe at this because you have to recompile to change the URL's, but how often are they going to change?

In the event, however, that you do want to include these CDN-distributed items on every page, what's wrong with throwing the URLs in your master page? In most cases, changing your master page is just as simple as changing a web.config value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top