I have the same problem as many that my images are not resolved when I bundle my CSS-Stylesheets.
Now I found some SO-Answers that suggest using new CssRewriteUrlTransform()
as second parameter for the "Include"-Method of a new StyleBundle-Object. This one for example
I'm using IncludeDirectory because I have a directory where I can add files without having them to register somewhere (and they are many files which I don't want to list). But IncludeDirectory doesn't have an override to pass a CssRewriteUrlTransform-Object:
Doesn't work: bundles.Add(new StyleBundle("~/bundles/css/directives").IncludeDirectory("~/app/directives", "*.css", true));
I also tried:
StyleBundle sb = new StyleBundle();
sb.Transforms.Add(new CssRewriteUrlTransform());
But Transforms are of Type IBundleTransform and I'm trying to pass an IItemTransform.
Any suggestions on how to do this?
As I didn't find a better answer, I'll post my solution (which feels more like a workaround):
public class BundleConfig {
private class CssRewriteUrlTransformWrapper : IItemTransform {
public string Process(string includedVirtualPath, string input) {
//see https://stackoverflow.com/questions/19765238/cssrewriteurltransform-with-or-without-virtual-directory
return new CssRewriteUrlTransform().Process("~" + VirtualPathUtility.ToAbsolute(includedVirtualPath), input);
}
}
private static string MakeVirtualPath(string fromPhysPath, string withVirtualPath) {
var res = fromPhysPath.Replace("\\", "/");
var idx = res.IndexOf(withVirtualPath.Replace("~", ""));
res = "~" + res.Substring(idx);
return res;
}
private static StyleBundle CreateStyleBundleForDir(string virtualPath) {
StyleBundle res = new StyleBundle(virtualPath + "/bundle");
string[] cssFilesPhysical = Directory.GetFiles(HttpContext.Current.Server.MapPath(virtualPath), "*.css", SearchOption.AllDirectories);
List<string> cssFilesVirtual = new List<string>();
foreach (var file in cssFilesPhysical) {
res.Include(MakeVirtualPath(file, virtualPath), new CssRewriteUrlTransformWrapper());
}
return res;
}
public static void RegisterBundles(BundleCollection bundles) {
bundles.Add(CreateStyleBundleForDir("~/app/custom"));
}
}
I'm open for constructive citicism :)