使用CssRewriteUrlTransform时,MVC的捆绑在CSS图像中返回错误的URL:
我有一个Intranet应用程序,其URL为,例如:http://usid01-srv002/MyApplication
。它位于IIS的“默认网站”中。
BundleConfig.cs
中有以下内容:
bundles.Add(new StyleBundle("~/bundles/jcss")
.Include("~/Scripts/JQueryUI/css/*.css", new CssRewriteUrlTransform())
);
捆绑系统正在为这些CSS文件中引用的任何图像生成错误的URL,从而产生404甚至是JQueryUI经过良好测试的CSS文件(来自FireBug):
e.g。它正在产生
http://usid01/path/foo.png
什么时候应该生成:
http://usid01/MyApplication/path/foo.png
如何让捆绑系统生成指向正确位置的URL?
答案 0 :(得分:49)
CssRewriteUrlTransform使用绝对路径更新CSS Url,如果我们使用的话,请说明 -
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css",new CssRewriteUrlTransform()));
我们在“site.css”中有以下CSS类
.Sandy
{
background-image: url("Images/Sandy.jpg");
border: 1px solid #c8c8c8;
border-radius:4px 4px 4px 4px;
box-shadow: 1px 1px 8px gray;
background-position:left;
background-size:contain;
-moz-background-size:contain;
-webkit-background-size:contain;
-o-background-size:contain;
background-repeat:no-repeat;
min-height:100px;
min-width:100px;
display:block;
}
以及以下文件夹结构 -
-Web site Root
-Content
--site.css
--Images
---Sandy.jpg
捆绑将为“background-image”生成以下CSS Url路径 -
background-image: url("/Content/Images/Sandy.jpg");
现在,如果你将网站/网络应用程序托管在网络服务器上面的路径上,那么 因为前导'/'
,浏览器将使用以下Url发送对此资源的请求http://<server>/content/images/sandy.jpg
但如果您将网站作为Web应用程序托管,则会产生问题。因为浏览器仍会将其解释为绝对Url而不是相对,并仍然发送以下请求来获取此资源 -
http://<server>/content/images/sandy.jpg
所以,这个问题的解决方案是使用相对Url甚至在CSS文件中,然后从Bundle配置中删除CssRewriteUrlTransform,如下所示 -
background-image: url("Images/Sandy.jpg");
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
答案 1 :(得分:6)
图像损坏的原因是它试图找到相对于在捆绑期间定义的新路径的图像,即
bundles.Add(new StyleBundle("~/Content/woothemes").Include( "~/Content/woothemes/css/style.css", ));
因此,如果在style.css中定义了任何图像路径(即背景图像),它将尝试获取相对于 Content / woothemes 而非 Content / woothemes / css的路径/ ,因此无法找到图像
解决同一文件夹的文件的问题的一种解决方法是定义与文件夹(其文件被缩小)相同的新路径,即
bundles.Add(new StyleBundle("~/Content/woothemes/css").Include( "~/Content/woothemes/css/style.css", ));
这样捆绑文件和实际文件路径将匹配,并且将找到css中定义的图像,因此问题将得到解决
如果您出于上述相同原因混合来自不同文件夹的文件,则只会解决此问题
答案 2 :(得分:3)
这对我有用,
<link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/content/styles/css")" rel="stylesheet" type="text/css" />