MVC捆绑和CSS相对URL

前端之家收集整理的这篇文章主要介绍了MVC捆绑和CSS相对URL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
MVC的捆绑在使用CssRewriteUrlTransform时返回CSS图像中的错误URL:

我有一个内部网应用程序的URL是,例如:http:// usid01-srv002 / MyApplication。它在IIS的“默认网站”。

其中在BundleConfig.cs中有以下:

  1. bundles.Add(new StyleBundle("~/bundles/jcss")
  2. .Include("~/Scripts/JQueryUI/css/*.css",new CssRewriteUrlTransform())
  3. );

绑定系统正在为这些CSS文件中引用的任何图像生成错误的URL,生成404的甚至JQueryUI的经过良好测试的CSS文件(来自FireBug):

例如它产生

  1. http://usid01/path/foo.png

当它应该产生:

  1. http://usid01/MyApplication/path/foo.png

如何使捆绑系统生成指向正确位置的URL?

解决方法

CssRewriteUrlTransform用绝对路径更新CSS网址,如果我们使用 –
  1. bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css",new CssRewriteUrlTransform()));

我们在“site.css”中有以下的CSS类

  1. .Sandy
  2. {
  3. background-image: url("Images/Sandy.jpg");
  4. border: 1px solid #c8c8c8;
  5. border-radius:4px 4px 4px 4px;
  6. Box-shadow: 1px 1px 8px gray;
  7. background-position:left;
  8. background-size:contain;
  9. -moz-background-size:contain;
  10. -webkit-background-size:contain;
  11. -o-background-size:contain;
  12. background-repeat:no-repeat;
  13. min-height:100px;
  14. min-width:100px;
  15. display:block;
  16. }

和以下文件夹结构 –

  1. -Web site Root
  2. -Content
  3. --site.css
  4. --Images
  5. ---Sandy.jpg

绑定将生成以下CSS Url路径“background-image” –

  1. background-image: url("/Content/Images/Sandy.jpg");

现在如果你托管的网站/ Web应用程序作为一个网站上面的Web服务器上面的路径将工作,
因为浏览器将使用以下网址发送此资源的请求,因为前导’/’

  1. http://<server>/content/images/sandy.jpg

但如果你托管网站作为Web应用程序这将创建问题。因为浏览器仍然会将此解释为绝对Url而不是相对的,并仍然发送以下请求来获取此资源 –

  1. http://<server>/content/images/sandy.jpg

所以,这个问题的解决方案是使用相对Url甚至在CSS文件,然后从Bundle配置中删除CssRewriteUrlTransform如下 –

  1. background-image: url("Images/Sandy.jpg");
  2.  
  3. bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

猜你在找的CSS相关文章