Avoiding problems with relative and absolute URLs in ASP.NET
I'm back to ASP.NET development, and the first thing that hits me in the face is the limitations with URL handling in ASP.NET.
I have an ASP.NET application which pages contain images. The images are represented using HTML's IMG tags. This is a common situation, I guess :-) The problem is simple: how should I express the URLs of my images?
I can think of five options:
- use relative paths.
Problems: If you move your files around, you'll need to change every path. If you use this in a User Control, the path will be relative to the page using the control, not to where the control file is. - use absolute paths.
Exemple: <img src="/Images/imgxx.png" />
Problem: This requires a specific web site for each application. Apart from being an additional difficulty for deployment and administration, this isn't possible on Windows XP, which allows only one IIS web site. - use a specific alias for the images.
Exemple: one alias named MyApp for the application, one alias named MyAppImages for the images, and images referring to /MyAppImages/imgxx.png.
Problem: multiplicating aliases can be a problem and add to the complexity of the application. - use ~ and runat="server" everywhere.
The tilde (~) character represents the root directory of the application in ASP.NET.
Exemple: <img runat="server" src="~/Images/imgxx.png" />.
Problem: Performance is hurt because your image tags are converted to server controls when the page needs to be generated, while there isn't really a need for this. - switch to Image web controls and use ~.
Problem: same as above, plus the fact that it makes converting from HTML pages to ASPX pages more difficult.
The solution I will probably choose is a sixth option: use <%=Request.ApplicationPath%> to prefix the URLs. Exemple: <img src="<%=Request.ApplicationPath%>/Images/imgxx.png" />
Which way do you go? Do you have a better solution?