Andornot Consulting
Wednesday, June 27, 2007 5:46 PM

Type-safe access to the current page's URL

by Ted Jardine

Virtually every web project you work on requires that you get the current page's complete URL. Years ago, I got tired of using non-type-safe ways of munging together various Request.ServerVariables to get it (anyone remember stuff like "If Request.ServerVariables("HTTPS") = "on" Then..."?) and with .NET there had to be a better way. Due to a dearth of non-Request.ServerVariables examples out there back then, it took trusty trial and error Response.Write tests and the MSDN help to settle on the following:

Request.Url.Scheme + Request.Url.SchemeDelimiter + Request.Url.Authority + Request.Url.PathAndQuery

While I never understood why I still had to parse these together (and I sporadically investigated alternatives), it nevertheless felt so much better than parsing together strings like "://" with icky stuff like Request.ServerVariables("SERVER_NAME").

But yes, there had to be an even better way: a way that resisted forgetfulness and the ensuing battle with more than vague intellisense descriptions. Since I'm slow, it was only today that I found it. My my, sometimes I do miss the obvious:

Request.Url.ToString()
returns the canonically unescaped form of the URI (i.e. "http://www.example.com:80//thick and thin.htm")

and/or

Request.Url.AbsoluteUri
Returns the canonically escaped form of the URI (i.e. http://www.example.com:80//thick%20and%20thin.htm)

And yes, I had tried out AbsoluteUri before (I must have, right?), but for some reason, I still missed it.

Comments

6/28/2007 10:27:00 AM #

Peter Tyrrell

Tell me about it! I had some trouble over the difference between Url.ToString() and Url.AbsoluteUri() a while back, in that I couldn't understand that Url.ToString() *always* returns the URL unencoded: URI gotcha post.

A related topic that we ought to explore is how to get just the current request URL up to the hostname, and no further, like http://www.andornot.com, with no path.

I've used this in the recent past, but there's probably something better:

string.Format("{0}{1}{2}", Request.Url.Scheme, Uri.SchemeDelimiter, Request.Url.Authority)

Not to mention, Control.ResolveUrl() and Control.ResolveClientUrl() could use some elucidation.

Peter Tyrrell | Reply

Add comment


(Will not be posted. Rather, will be used to show your Gravatar icon.)

  Country flag

biuquote
  • Comment
  • Preview
Loading