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);

25 Comments

Comments have been disabled for this content.