How can I get the baseurl of site?

C#asp.netUriHttprequest

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Try this:

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

Solution 2 - C#

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

That's it ;)

Solution 3 - C#

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

Solution 4 - C#

This is a much more fool proof method.

VirtualPathUtility.ToAbsolute("~/");

Solution 5 - C#

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

Solution 6 - C#

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.

Solution 7 - C#

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;

Solution 8 - C#

I go with

HttpContext.Current.Request.ServerVariables["HTTP_HOST"]

Solution 9 - C#

This works for me.

Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "") + Request.ApplicationPath;
  • Request.Url.OriginalString: return the complete path same as browser showing.
  • Request.Url.PathAndQuery: return the (complete path) - (domain name + PORT).
  • Request.ApplicationPath: return "/" on hosted server and "application name" on local IIS deploy.

So if you want to access your domain name do consider to include the application name in case of:

  1. IIS deployment
  2. If your application deployed on the sub-domain.

====================================

For the dev.x.us/web

it return this strong text

Solution 10 - C#

I'm using following code from Application_Start

String baseUrl = Path.GetDirectoryName(HttpContext.Current.Request.Url.OriginalString);

Solution 11 - C#

Please use the below code                           

string.Format("{0}://{1}", Request.url.Scheme, Request.url.Host);

Solution 12 - C#

you could possibly add in the port for non port 80/SSL?

something like:

if (HttpContext.Current.Request.ServerVariables["SERVER_PORT"] != null && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "80" && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "443")
            {
                port = String.Concat(":", HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString());
            }

and use that in the final result?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJagguView Question on Stackoverflow
Solution 1 - C#Frank AllenbyView Answer on Stackoverflow
Solution 2 - C#WarlockView Answer on Stackoverflow
Solution 3 - C#Todd MenierView Answer on Stackoverflow
Solution 4 - C#Daniel A. WhiteView Answer on Stackoverflow
Solution 5 - C#rufoView Answer on Stackoverflow
Solution 6 - C#cirrusView Answer on Stackoverflow
Solution 7 - C#SpazDudeView Answer on Stackoverflow
Solution 8 - C#TalhaView Answer on Stackoverflow
Solution 9 - C#FAHIDView Answer on Stackoverflow
Solution 10 - C#Crispijn LangeView Answer on Stackoverflow
Solution 11 - C#Pranav JosephView Answer on Stackoverflow
Solution 12 - C#Mark RedmanView Answer on Stackoverflow