Get the url to the virtual root for the current request

Sometimes you get into the situation that you have to build a Url within the current request to a page that you know the virtual path for, but it has to be on the same server as the current request. The problem is to find the url for the virtual root of the request. So for the request https://server:1234/myfolder/mypage.aspx we need to find https://server:1234.

Often you see code like:

Uri requestUri = Context.Request.Url;
string baseUrl = requestUri.Scheme + Uri.SchemeDelimiter + requestUri.Host + (requestUri.IsDefaultPort ? "" : ":" + requestUri.Port);

This can be done much easier with the following code:

string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);

Published Monday, July 03, 2006 1:04 AM by svdoever
Filed under:

Comments

Monday, July 03, 2006 10:13 AM by Jason Haley

# Interesting Finds: July 3, 2006

Sunday, July 09, 2006 11:54 PM by Christopher Steen

# Link Listing - July 9, 2006

A slider client control for Atlas [Via: bleroy ] ADO.NET and SQL Server Everywhere [Via: alexbarn...

Thursday, January 25, 2007 4:03 PM by everest

# re: Get the url to the virtual root for the current request

thanks. it's very helpful

Thursday, August 09, 2007 12:51 PM by Alok Pagariya

# re: Get the url to the virtual root for the current request

That is was i was looking for.

Thanks A Lot

Wednesday, September 12, 2007 11:58 AM by Jen

# re: Get the url to the virtual root for the current request

This is great! Exactly what i was looking for.

Thank you

Wednesday, September 12, 2007 12:02 PM by Jen

# re: Get the url to the virtual root for the current request

This is great! Exactly what i was looking for.

Thank you

Thursday, October 25, 2007 2:51 PM by Premnath

# re: Get the url to the virtual root for the current request

Excellent!... Thanks a lot

Thursday, November 22, 2007 3:01 AM by Fern Gilliput

# re: Get the url to the virtual root for the current request

YAY! Just what I always wanted!

Tuesday, February 26, 2008 4:18 AM by Tobias Zimmergren

# re: Get the url to the virtual root for the current request

Nice tip, my initial approach was similar to the code you mentioned first. However this shortened it quite a bit.

Cheers

Leave a Comment

(required) 
(required) 
(optional)
(required)