Cha*_*rns 45 css asp.net-mvc relative-path bundling-and-minification asp.net-mvc-5
使用CssRewriteUrlTransform时,MVC的捆绑在CSS图像中返回错误的URL:
我有一个内联网应用程序,其URL是,例如:http://usid01-srv002/MyApplication.它位于IIS的"默认网站"中.
其中包含以下内容BundleConfig.cs:
bundles.Add(new StyleBundle("~/bundles/jcss")
.Include("~/Scripts/JQueryUI/css/*.css", new CssRewriteUrlTransform())
);
Run Code Online (Sandbox Code Playgroud)
捆绑系统为这些CSS文件中引用的任何图像生成错误的URL,从而产生404甚至JQueryUI经过良好测试的CSS文件(来自FireBug):

例如,它正在产生
http://usid01/path/foo.png
Run Code Online (Sandbox Code Playgroud)
什么时候应该生成:
http://usid01/MyApplication/path/foo.png
Run Code Online (Sandbox Code Playgroud)
如何让捆绑系统生成指向正确位置的URL?
Bha*_*a K 49
CssRewriteUrlTransform用绝对路径更新CSS Url,如果我们使用的话,请说 -
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css",new CssRewriteUrlTransform()));
Run Code Online (Sandbox Code Playgroud)
我们在"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;
}
Run Code Online (Sandbox Code Playgroud)
和以下文件夹结构 -
-Web site Root
-Content
--site.css
--Images
---Sandy.jpg
Run Code Online (Sandbox Code Playgroud)
捆绑将为"background-image"生成以下CSS Url路径 -
background-image: url("/Content/Images/Sandy.jpg");
Run Code Online (Sandbox Code Playgroud)
现在,如果您将网站/ Web应用程序作为Web服务器上的网站托管,则路径将起作用,因为浏览器将使用以下Url发送此资源的请求,因为前导'/'
http://<server>/content/images/sandy.jpg
Run Code Online (Sandbox Code Playgroud)
但如果您将网站作为Web应用程序托管,则会产生问题.因为浏览器仍会将其解释为绝对Url而不是相对的,并且仍然发送以下请求来获取此资源 -
http://<server>/content/images/sandy.jpg
Run Code Online (Sandbox Code Playgroud)
因此,此问题的解决方案是使用相对Url甚至在CSS文件中,然后从Bundle配置中删除CssRewriteUrlTransform,如下所示 -
background-image: url("Images/Sandy.jpg");
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
Run Code Online (Sandbox Code Playgroud)
图像损坏的原因是它试图找到相对于在捆绑期间定义的新路径的图像,即
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中定义的图像,因此问题将得到解决
如果您出于上述相同的原因混合来自不同文件夹的文件,则只会解决此问题
小智 5
这对我有用,
<link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/content/styles/css")" rel="stylesheet" type="text/css" />
Run Code Online (Sandbox Code Playgroud)