我的一些样式使用url(../ img / sprites / main_sprite.png)来开发和阶段中的本地资源.但是在生产中我使用CDN并且我的所有静态资源都在其上.是否有可能转换bundle以使.css中的所有url都被cdn路径替换?
例如:
.logo { background-image: url(../img/sprites/main_sprite.png); }
但是,在制作中我希望如此
.logo { background-image: url(http://MyCdn.com/img/sprites/main_sprite.png); }
我已经使用CssRewriteUrlTransform()将我的相对路径重写为绝对路径,因此可以在捆绑后找到资源.
我正在考虑将课程扩展为类似的东西
public string Process(string includedVirtualPath,string input) { if (_useCdn) { return new CssRewriteUrlTransform().Process(_cdn + VirtualPathUtility.ToAbsolute(includedVirtualPath),input); } else { return new CssRewriteUrlTransform().Process("~" + VirtualPathUtility.ToAbsolute(includedVirtualPath),input); } }
但是,Process必须具有VirtualPath,否则在我追加CDN路径时会抛出异常.
是否有相应的这个类用它来重写带有CDN的URL?
解决方法
我无法找到现有的解决方案.所以,我使用CssRewriteUrlTransform代码作为我的CDNStylesTransformer的基础.我希望它对你也有用.
/// <summary> /// Finds and Replaces Urls with CDN links. /// </summary> public class CDNStylesTransformer : IItemTransform { private bool _useCdn; private string _cdnBaseUrl; public CDNStylesTransformer(bool UseCDN,string CdnBaseUrl) { _useCdn = UseCDN; if(CdnBaseUrl == null || CdnBaseUrl.Equals(string.Empty)) { throw new ArgumentNullException("CdnBaseUrl"); } _cdnBaseUrl = CdnBaseUrl; } internal static string RebaseUrlToCDNUrl(string cdnUrl,string url) { // Don't do anything to invalid urls or absolute urls if (String.IsNullOrWhiteSpace(url) || String.IsNullOrWhiteSpace(url) || url.StartsWith("data:") || !VirtualPathUtility.IsAbsolute(url)) { return url; } return cdnUrl + url; } internal static string ConvertUrlsToCDNUrl(string cdnUrl,string content) { if (String.IsNullOrWhiteSpace(content)) { return content; } // Replace all urls with CDN urls Regex url = new Regex(@"url\(['""]?(?<url>[^)]+?)['""]?\)"); return url.Replace(content,((match) => { return "url(" + RebaseUrlToCDNUrl(cdnUrl,match.Groups["url"].Value) + ")"; })); } public string Process(string includedVirtualPath,string input) { if (_useCdn) { return ConvertUrlsToCDNUrl(_cdnBaseUrl,input); } else { return input; //do nothing } } }
在BundleConfiguration类中
string cdnPath ="http://MyCdn.com"; bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( "~/Content/themes/base/style1.css",new CDNStylesTransformer(bundles.UseCdn,cdnPath) ));