I\'m using the ASP.NET MVC 4 bundling and minifying features in the Microsoft.AspNet.Web.Optimization namespace (e.g. @Styles.Render(\"~/content/static/css\")).
For @manishKungwani requested in previous comment. Just set UseCdn and then use the cdnHost overload to crate the bundle. I used this to put in an AWS CloudFront domain (xxx.cloudfront.net) but in hindsight it should have been named more generically to use with any other CDN provider.
public class CloudFrontScriptBundle : Bundle
{
public CloudFrontScriptBundle(string virtualPath, string cdnHost = "")
: base(virtualPath, null, new IBundleTransform[] { new JsMinify(), new CloudFrontBundleTransformer { CdnHost = cdnHost } })
{
ConcatenationToken = ";";
}
}
public class CloudFrontStyleBundle : Bundle
{
public CloudFrontStyleBundle(string virtualPath, string cdnHost = "")
: base(virtualPath, null, new IBundleTransform[] { new CssMinify(), new CloudFrontBundleTransformer { CdnHost = cdnHost } })
{
}
}
public class CloudFrontBundleTransformer : IBundleTransform
{
public string CdnHost { get; set; }
static CloudFrontBundleTransformer()
{
}
public virtual void Process(BundleContext context, BundleResponse response)
{
if (context.BundleCollection.UseCdn && !String.IsNullOrWhiteSpace(CdnHost))
{
var virtualFileName = VirtualPathUtility.GetFileName(context.BundleVirtualPath);
var virtualDirectory = VirtualPathUtility.GetDirectory(context.BundleVirtualPath);
if (!String.IsNullOrEmpty(virtualDirectory))
virtualDirectory = virtualDirectory.Trim('~');
var uri = string.Format("//{0}{1}{2}", CdnHost, virtualDirectory, virtualFileName);
using (var hashAlgorithm = CreateHashAlgorithm())
{
var hash = HttpServerUtility.UrlTokenEncode(hashAlgorithm.ComputeHash(Encoding.Unicode.GetBytes(response.Content)));
context.BundleCollection.GetBundleFor(context.BundleVirtualPath).CdnPath = string.Format("{0}?v={1}", uri, hash);
}
}
}
private static SHA256 CreateHashAlgorithm()
{
if (CryptoConfig.AllowOnlyFipsAlgorithms)
{
return new SHA256CryptoServiceProvider();
}
return new SHA256Managed();
}
}