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 ur
I go with
HttpContext.Current.Request.ServerVariables["HTTP_HOST"]
Try this:
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
Request.ApplicationPath.TrimEnd('/') + "/";
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority)
That's it ;)
I'm using following code from Application_Start
String baseUrl = Path.GetDirectoryName(HttpContext.Current.Request.Url.OriginalString);
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);
Based on what Warlock wrote, I found that the virtual path root is needed if you aren't hosted at the root of your web. (This works for MVC Web API controllers)
String baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority)
+ Configuration.VirtualPathRoot;