Search code examples
c#asp.net-mvc-4bundling-and-minificationweb-optimization

CssRewriteUrlTransform with or without virtual directory


We are using MVC Bundling in our site, CssRewriteUrlTransform makes sure that the image urls work from the dynamic bundle css file.

But this only works when not using a virtual directory, i.e

http://localhost/VirttualDir does not work but http://localhost/ does. This is because the CssRewriteUrlTransform tranform does not take the virtual folder into account when rewriting the url. So if a image real path is localhost/vdir/content/img/foo.png it will rewrite it to localhost/content/img/foo.png which is wrong


Solution

  • I am not sure to fully understand your problem, but seeing http://localhost here seems wrong. You should never use an absolute URL for your bundles.

    For me CssRewriteUrlTransform works perfectly, here is how I use it:

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

    "Bundles" is virtual.

    Does this helps?

    Update

    I was confused with the "VirtualDir" thing, as you are talking about IIS VirtualDir, and I was thinking Bundle VirtualDir! It's true that in this case CssRewriteUrlTransform will rewrite URLs to the Host, not to the Host/VirtualDir URI.

    To do that, you have to derive CssRewriteUrlTransform to make it do what you need it to. There is a good discussion here: ASP.NET MVC4 Bundling with Twitter Bootstrap

    Seems the best answer is there:http://aspnetoptimization.codeplex.com/workitem/83

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

    Use this class instead of CssRewriteUrlTransform