The URI class is one that I often forget about. In fact, I got an email from
Scott Mitchell today asking about some alternate code to establish a 'base path'.
Sometimes you need to find out a base path in order to use it inside of a page so that images and related links can load properly. Oddly enough you can get the application path but it's not a full URL, only an application relative path.
The base path in this scenario would be:
Original Url
http://www.west-wind.com/wwStore/admin/default.aspx
Base Path
http://www.west-wind.com/wwStore
To get this I used code like this:
string Port = Request.ServerVariables["SERVER_PORT"];
if (Port == null || Port == "80" || Port == "443")
Port = "";
else
Port = ":" + Port;
string Protocol = Request.ServerVariables["SERVER_PORT_SECURE"];
if (Protocol == null || Protocol == "0")
Protocol = "http://";
else
Protocol = "https://";
this.BasePath = Protocol + Request.ServerVariables["SERVER_NAME"] +
Port + Request.ApplicationPath;
While this works, manual URL parsing is pretty slow and cumbersome. The shortcut to this is to use the URI class from Request.Url:
this.BasePath = Request.Url.GetLeftPart( UriPartial.Authority ) +
this.ResolveUrl( Request.ApplicationPath) ;
It pays to remember the URI class - shorter code and more reliable parsing of URLs from the framework.
Other Posts you might also like