OdeToCode IC Logo

URL-Rewriting breaks my HREFs

Monday, June 26, 2006

Q: I've been using the RewritePath method of the HttpContext class to rewrite URLs since ASP.NET 1.1. Everything was working until I moved my CSS files inside an ASP.NET 2.0 Theme directory. ASP.NET automatically writes out link tags for my stylesheets, but the href inside is broken. How do I fix this problem?

A: When rewriting URLs, don't use the RewritePath method that only accepts a path parameter, use the new overload that accepts a path parameter and a rebaseClientPath parameter. Pass a value of false for rebaseClientPath and the auto-magic injection of stylesheets will work.

Full explanation: The href in the stylesheet link provided by ASP.NET is a relative URL computed by Control.ResolveClientUrl. ResolveClientUrl is computing a path relative to the rewritten URL, not the original URL. Unfortunately, the relative URL won't work in the browser, because the browser is using the original URL.

By default, RewritePath rewrites a private field in the HttpRequest class by the name of _clientBaseDir. This field is used by Control.ResolveClientUrl to compute the relative URL. Passing false in the overloaded version of RewritePath tells the method to not rewrite this field. ResolveClientUrl will then use the original URL (the same URL the browser is using) when calculating relative URL, so everything works, and harmony remains.