Request.ApplicationPath - may cause unexpected results when using in pages at root level...
One of the first .NET tricks I learnt was from IBuySpy; they showed me how I could sneakily use Request.ApplicationPath
so that my sites could seamlessly work when I'm developing against different domains (such as Localhost in development). To perform the "trick" you simply prepend <%= Request.ApplicationPath %> to the beginning of any paths in your pages, such as:
<img src='<%= Request.ApplicationPath %>/Images/Foo.gif' ... />
The problem is that, when a file is requested, it is returned "root-relative" without a trailing slash. This means that when a page is requested from the root folder of a Website, Request.ApplicationPath
returns '/'. In the above example the following string will be written out:
<img src='//Images/Foo.gif' ... />
This wouldn't be picked up when developing against localhost because the application will be one level under the root of the Website meaning that the virtual directory name will be returned after the slash '/':
<img src='/ApplicationName/Images/Foo.gif' ... />
However, if a page is requested from a page in a sub-folder, then the path is returned as "/FldrName" and the above example will resolve correctly as:
' From the root <img src='/FldrName/Images/Foo.gif' ... /> ' In a virtual directory <img src='/ApplicationName/FldrName/Images/Foo.gif' ... />
So, is there a single answer for developing on root and virtual directories - I'm not sure. The easiest way is to simply add all of your pages under a sub-folder (which I believe is done in the case of IBuySpy). That's too bad if you've already got a site with all of its pages in the root folder though :(