How can I get the baseurl of site?
I want to write a little helper method which returns the base URL of the site. This is what I came up with:
public static string GetSiteUrl()
{
string url = string.Empty;
HttpRequest request = HttpContext.Current.Request;
if (request.IsSecureConnection)
url = "https://";
else
url = "http://";
url += request["HTTP_HOST"] + "/";
return url;
}
Is there any mistake in this, that you can think of? Can anyone improve upon this?
Try this:
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
Request.ApplicationPath.TrimEnd('/') + "/";
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority)
That's it ;)
The popular GetLeftPart
solution is not supported in the PCL version of Uri
, unfortunately. GetComponents
is, however, so if you need portability, this should do the trick:
uri.GetComponents(
UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);
I believe that the answers above doesn't consider when the site is not in the root of the website.
This is a for WebApi controller:
string baseUrl = (Url.Request.RequestUri.GetComponents(
UriComponents.SchemeAndServer, UriFormat.Unescaped).TrimEnd('/')
+ HttpContext.Current.Request.ApplicationPath).TrimEnd('/') ;
To me, @warlock's looks like the best answer here so far, but I've always used this in the past;
string baseUrl = Request.Url.GetComponents(
UriComponents.SchemeAndServer, UriFormat.UriEscaped)
Or in a WebAPI controller;
string baseUrl = Url.Request.RequestUri.GetComponents(
UriComponents.SchemeAndServer, UriFormat.Unescaped)
which is handy so you can choose what escaping format you want. I'm not clear why there are two such different implementations, and as far as I can tell, this method and @warlock's return the exact same result in this case, but it looks like GetLeftPart()
would also work for non server Uri's like mailto
tags for instance.