Making Sense of ASP.Net Paths

I was just considering writing this yesterday for my own reference, due to some good comments by Roger Lipscombe on my path calls in my RewritePath article.

I found this article by Rick Strahl that summed up all the options working with paths, along with a comment from one of the ASP.Net v2 developers, Shanku Niyogi about using the Uri class to work with urls whenever possible.  His comment follows:

It's best to avoid putting URLs together using string concatenation at all. I could go into all the details and lessons learned (canonicalization problems, etc.), but the bottom line is to try to use the Uri class to put together URLs wherever possible. In Whidbey, we're making the Uri class a lot more performant, by not making it inherit from MarshalByRefObject.

This is especially true of an ASP.NET app, because if you're ever constructing a full URL, you may need to add in the cookieless session ID into the path (and any other info you write into a path).

So, what to do? A handy method on the ASP.NET Control class (and thus also on the Page class), called ResolveUrl, will convert a relative URL to an appropriate root-relative URL. Because this uses the TemplateSourceDirectory property, it will also work with relative URLs in a user control that exists in a directory different from the page. This is how ASP.NET server controls resolve relative URLs.

For example, if /default.aspx includes controls/control1.ascx, and the control calls ResolveUrl on "foo.gif", you'll get "/controls/foo.gif". If you are using cookieless session state, the session ID will automatically be inserted into this URL.

Print | posted on Friday, October 01, 2004 10:02 AM

Feedback

No comments posted yet.
Title  
Name
Email (never displayed)
Url
Comments   
Please add 3 and 1 and type the answer here: