MVC Bundling and CSS relative URLs

≡放荡痞女 提交于 2019-11-27 03:33:46

CssRewriteUrlTransform updates the CSS Url with absolute path, saying so if we use -

bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css",new CssRewriteUrlTransform()));

and we have following CSS class in "site.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;
}

and following folder structure -

   -Web site Root
   -Content
   --site.css
   --Images
   ---Sandy.jpg

Bundling will generate following CSS Url Path for "background-image" -

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

And now if you hosting the website / web application as a website on web server above path will work, because browser will send request for this resource using following Url because of leading '/'

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

but if you host the website as web application this will create problem. Because browser will still interpret this as absolute Url instead of relative and still send following request to fetch this resource -

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

So, the solution for this problem is using the relative Url even in CSS file and then remove the CssRewriteUrlTransform from the Bundle config as below -

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

bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

The reason for the broken images is that it tries to find the images relative to the new path defined during bundling i.e.

bundles.Add(new StyleBundle("~/Content/woothemes").Include(
            "~/Content/woothemes/css/style.css",
));

So if there is any image path (i.e. background image) defined in style.css, it will try to get its path relative to Content/woothemes instead of Content/woothemes/css/, hence the images will not be found

One workaround to overcome the issue for the files of same folder is to define the new path same as that of the folder (whose files are being minified) i.e.

bundles.Add(new StyleBundle("~/Content/woothemes/css").Include(
            "~/Content/woothemes/css/style.css",
));

This way the bundled files and the actual files path will match and the images defined in the css will be found, hence the issue will be resolved

The issue will only not be resolved if you mix the files from different folders for the same reason described above

This works for me,

<link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/content/styles/css")" rel="stylesheet" type="text/css" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!