当我捆绑CSS-Stylesheets时,我遇到的问题与我的图像没有解决的问题一样。
现在我发现一些SO-Answers建议使用new CssRewriteUrlTransform()
作为新的StyleBundle-Object的" Include" -Method的第二个参数。 This one for example
我正在使用IncludeDirectory,因为我有一个目录,我可以添加文件而无需在某处注册(而且它们是我不想列出的许多文件)。但IncludeDirectory没有覆盖传递CssRewriteUrlTransform-Object:
不起作用: bundles.Add(new StyleBundle("~/bundles/css/directives").IncludeDirectory("~/app/directives", "*.css", true));
我也尝试过:
StyleBundle sb = new StyleBundle();
sb.Transforms.Add(new CssRewriteUrlTransform());
但是Transforms属于IBundleTransform类型,我试图通过IItemTransform。
有关如何执行此操作的任何建议吗?
答案 0 :(得分:2)
由于我没有找到更好的答案,我会发布我的解决方案(感觉更像是一种解决方法):
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"));
}
}
我愿意接受建设性的中国主义:)
答案 1 :(得分:2)
将此扩展方法添加到BundleConfig并将其用作
new StyleBundle("~/Bundles/all.css")
.InclDir("~/WebResources/libref/minton/css", "*.css");
代码:
private static void InclDir(this StyleBundle bundles, string virtualPath, string pattern, bool includeSubDir = false)
{
var vpath = virtualPath.TrimEnd('/');
var ppath = HttpContext.Current.Server.MapPath(vpath);
var files = Directory.GetFiles(ppath, pattern, includeSubDir ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
foreach (var file in files)
{
var vfp = virtualPath + "/" + file.Substring(ppath.Length + 1).Replace("\\", "/");
bundles.Include(vfp, new CssRewriteUrlTransform());
}