首页 > 解决方案 > StyleBundle 打破相对路径

问题描述

我的问题与此类似:

将网站部署到应用程序时的 mvc 捆绑和相关 css 图像

MVC4 StyleBundle 无法解析图像

总结:

在 css 中使用相对链接时,链接将在捆绑后断开。

例子:

原来的:

.flags {
  background-image: url("../images/flags.png");
}

对服务器的请求:

GET https://{HOST}/myapp/images/flags.png 200

捆绑后:

.flags {background-image: url("../images/flags.png");}

对服务器的请求:

GET https://{HOST}/images/flags.png 404

我想要什么(捆绑后)

.flags {background-image: url("/myapp/images/flags.png");}

或者

.flags {background-image: url("images/flags.png");}

我的 BundleConfig.cs

using System.Web;
using System.Web.Optimization;

namespace MyApp
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            // CSS
            bundles.Add(new StyleBundle("~/App/bundledCSS")
                .Include("~/App/css/index.css", new CssRewriteUrlTransformWrapper())
               );

            [JS Bundels, ...]
        }
    }

    public class CssRewriteUrlTransformWrapper : IItemTransform
    {
        public string Process(string includedVirtualPath, string input)
        {
            return new CssRewriteUrlTransform().Process("~" + VirtualPathUtility.ToAbsolute(includedVirtualPath), input);
        }
    }
}

在我的 index.cshtml

@Styles.Render("~/App/bundledCSS")

我尝试了两者的解决方案,但没有得到有效的结果

我使用的其他资源:

捆绑时更改对 CSS 文件的相对 URL 引用

如何在 StyleBundle 中设置图像路径?

此外,很高兴知道是否可以使用该解决方案IncludeDirectory或使其StyleBundle影响 a 中的所有样式

例子:

bundles.Add(new StyleBundle("~/App/bundledCSS")
               .IncludeDirectory("~/App/css/other", "*.css", true)
               .IncludeDirectory("~/App/css/lib", "*.css", true);

标签: c#cssasp.net.netweb-optimization

解决方案


推荐阅读