10

To convert relative image paths to absolute path there are many questions asked and answered in stackoverflow like this one:

MVC4 StyleBundle not resolving images

that suggest adding new CssRewriteUrlTransform() as below:

bundles.Add(new StyleBundle("~/Content/css/jquery-ui/bundle")
       .Include("~/Content/css/jquery-ui/*.css", new CssRewriteUrlTransform()));

and this actually have saved me before. but now that I deploy my website to an application (not root of a website) there is still a problem:

the application is:

http://localhost/sample/

but the image urls are like:

http://localhost/css/imgs/spirit.png

while it should be:

 http://localhost/sample/css/imgs/spirit.png

although the bundled css link itself is correct and working.

Community
  • 1
  • 1
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171

2 Answers2

8

If there are no virtual directories involved the following code would do:

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

but when VirtualDirectory is used CssRewriteUrlTransform will rewrite to Host instead of Host/VirtualDirectory. the solution is to derive CssRewriteUrlTransform which is fully discussed here: ASP.NET MVC4 Bundling with Twitter Bootstrap:

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

This is actually just another issue with optimizations in general not working correctly when the app is running as a virtual directory.

Since you're using a virtual directory for hosting your website, So you should make a wrapper that will call CssRewriteUrlTransform with the fixed path:

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

More info.

Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110