Join the DZone community and get the full member experience.Join For Free
Our solution is simple. We will add new configuration setting to our web.config file (including cloud transform file of it) and new property to our web application. In master page where scripts are included we will include scripts from CDN conditionally. There is nothing complex, all changes we make are simple ones.
1. Adding new property to web application
Although I am using ASP.NET MVC web application these modifications work also very well with ASP.NET Forms. Open Global.asax and add new static property to your application class.
public static bool UseCdnIf you want less round-trips to configuration data you can keep some nullable boolean in your application class scope and load CDN setting first time it is asked.
var valueString = ConfigurationManager.AppSettings["useCdn"];
bool.TryParse(valueString, out useCdn);
2. Adding new configuration setting to web.config
By default my application uses local scripts. Although my application runs on cloud I can do a lot of stuff without staging environment in cloud. So by default I don’t have costs on traffic when including scripts from application folders.
<appSettings>You can also set UseCdn value to true and change it to false when you are not connected to network.
<add key="UseCdn" value="false" />
3. Modifying web.config cloud transform
I have special configuration for my solution that I use when deploying my web application to cloud. This configuration is called Cloud and transform for this configuration is located in web.cloud.config. To make application using CDN when deployed to cloud we need the following transform.
<appSettings>Now when you publish your application to cloud it uses CDN by default.
4. Including scripts in master pages
The last thing we need to change is our master page. My solution is simple. I check if I have to include scripts from CDN and if it is true then I include scripts from there. Otherwise my scripts will be included from application folder.
@if (MyWeb.MvcApplication.UseCdn)Although here is only one script shown you can add all your scripts that are also available in some CDN in this if-else block. You are free to include scripts from different CDN services if you need.
Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.