我正在使用移动设备,因此对于简短的回复,我深表歉意,但我稍后会更新。
Read this
长话短说,这与捆绑后相对路径被污染有关。但好消息是最新的捆绑库解决了它。
更新
为了填补空白,基本上发生的事情是 CSS 文件具有资源的相对路径(在本例中为图标精灵)。在调试模式下,文件单独输出到页面,因此保留引用(/Content/bootstrap.css 引用 images/glyphicons-halflings.png(制作完整路径 /Content/images/glyphicons-halflings.png)。但是,当调试被删除时,文件被捆绑并该路径现在是相对于您提供捆绑包的任何虚拟路径。在上述情况下,您现在来自 /bundles/maincss,这会导致错误的 /bundles/maincss/images/glyphicons-halflings.png 路径。
好消息是这是一个resolved bug,从Microsoft.AspNet.Web.Optimization v1.1.0 开始,您现在拥有CssRewriteUrlTransform,它将用绝对路径对应的路径替换所有相对路径(在CSS 文件中)。这意味着无论您如何调用捆绑包,资源仍然会被解析。
因此,要解决此问题,您可以简单地执行以下操作:
IItemTransform cssFixer = new CssRewriteUrlTransform();
bundles.Add(
new StyleBundle("~/bundles/maincss")
.Include("~/Content/bootstrap.css", cssFixer)
.Include("~/Content/bootstrap-responsive.css", cssFixer)
.Include("~/Content/my.css", cssFixer)
);
我唯一的疑虑是当你想要多个文件时这看起来有多难看,所以要解决这个问题,你可以使用扩展方法来简化它:
/// <summary>
/// Includes the specified <paramref name="virtualPaths"/> within the bundle and attached the
/// <see cref="System.Web.Optimization.CssRewriteUrlTransform"/> item transformer to each item
/// automatically.
/// </summary>
/// <param name="bundle">The bundle.</param>
/// <param name="virtualPaths">The virtual paths.</param>
/// <returns>Bundle.</returns>
/// <exception cref="System.ArgumentException">Only available to StyleBundle;bundle</exception>
/// <exception cref="System.ArgumentNullException">virtualPaths;Cannot be null or empty</exception>
public static Bundle IncludeWithCssRewriteTransform(this Bundle bundle, params String[] virtualPaths)
{
if (!(bundle is StyleBundle))
{
throw new ArgumentException("Only available to StyleBundle", "bundle");
}
if (virtualPaths == null || virtualPaths.Length == 0)
{
throw new ArgumentNullException("virtualPaths", "Cannot be null or empty");
}
IItemTransform itemTransform = new CssRewriteUrlTransform();
foreach (String virtualPath in virtualPaths)
{
if (!String.IsNullOrWhiteSpace(virtualPath))
{
bundle.Include(virtualPath, itemTransform);
}
}
return bundle;
}
这使得上面的代码更加简洁。 (可以说我选择了一个长方法名,但我喜欢保持方法名明确目的)
bundles.Add(
new StyleBundle("~/bundles/maincss").IncludeWithCssRewriteTransform(
"~/Content/bootstrap.css",
"~/Content/bootstrap-responsive.css",
"~/Content/my.css"
)
);