c# - How can I get the baseurl of site?

ID : 20064

viewed : 59

Tags : c#asp.neturihttprequestc#

Top 5 Answer for c# - How can I get the baseurl of site?

vote vote

100

Try this:

string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +      Request.ApplicationPath.TrimEnd('/') + "/"; 
vote vote

84

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

That's it ;)

vote vote

76

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

68

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('/') ; 
vote vote

52

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.

Top 3 video Explaining c# - How can I get the baseurl of site?

Related QUESTION?