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.
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.
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