Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save janv8000/fa69b2ab6886f635e3df to your computer and use it in GitHub Desktop.
Save janv8000/fa69b2ab6886f635e3df to your computer and use it in GitHub Desktop.
CssRewriteUrlTransform data URI workaround
/// <remarks>Part of Microsoft.AspNet.Web.Optimization.1.1.3, forked to ignore data-uri</remarks>
public class CssRewriteUrlTransformIgnoringDataUri : IItemTransform
{
internal static string RebaseUrlToAbsolute(string baseUrl, string url)
{
if (string.IsNullOrWhiteSpace(url) || string.IsNullOrWhiteSpace(baseUrl) || url.StartsWith("/", StringComparison.OrdinalIgnoreCase))
return url;
if (!baseUrl.EndsWith("/", StringComparison.OrdinalIgnoreCase))
baseUrl = baseUrl + "/";
return VirtualPathUtility.ToAbsolute(baseUrl + url);
}
internal static string ConvertUrlsToAbsolute(string baseUrl, string content)
{
if (string.IsNullOrWhiteSpace(content))
{ return content; }
return new Regex("url\\(['\"]?(?<url>[^)]+?)['\"]?\\)").Replace(content, match =>
{
var format = match.Groups["url"].Value;
if (format.StartsWith("data:image", StringComparison.CurrentCultureIgnoreCase))
{
return format;
}
return "url(" + RebaseUrlToAbsolute(baseUrl, format) + ")";
});
}
public string Process(string includedVirtualPath, string input)
{
if (includedVirtualPath == null)
{
throw new ArgumentNullException("includedVirtualPath");
}
return ConvertUrlsToAbsolute(VirtualPathUtility.GetDirectory(includedVirtualPath.Substring(1)), input);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment