200

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?

Vikrant
  • 4,920
  • 17
  • 48
  • 72
Jaggu
  • 6,298
  • 16
  • 58
  • 96
  • Check this http://stackoverflow.com/questions/3933662/in-asp-net-what-is-the-quickest-way-to-get-the-base-url-for-a-request – Sandeep G B Sep 14 '11 at 08:41
  • 1
    possible duplicate of [How can I get my webapp's base URL in ASP.NET MVC?](http://stackoverflow.com/questions/1288046/how-can-i-get-my-webapps-base-url-in-asp-net-mvc) – Serj Sagan Oct 14 '13 at 19:07

12 Answers12

367

Try this:

string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + 
    Request.ApplicationPath.TrimEnd('/') + "/";
Andomar
  • 232,371
  • 49
  • 380
  • 404
Frank Allenby
  • 4,332
  • 1
  • 17
  • 17
  • 14
    This is the only answer I've found that deals with the case where a site an application which is a child of a top level website in IIS. – John Mar 01 '13 at 10:49
  • 6
    string.Format("{0}{1}/", Request.Url.GetLeftPart(UriPartial.Authority), Request.ApplicationPath.TrimEnd('/')) – diegohb Oct 21 '13 at 20:17
  • 2
    Request.Url.Scheme does not always work when you have internal http configured and SSL termination set up for https internally on a server, but running https* outside. To get around this, I simply made an environment specific AppSetting Key "UrlScheme" with value of either "http" or "https" based on where the website resides. This setting in the web.config can be accessed by ConfigurationManager.AppSettings["Key"] – Ben Sewards Jan 15 '14 at 22:51
  • 4
    This doesn't take into account load balancing, where decryption occurs, or forward proxies. You can end up with an incorrect address using this, so be careful and know where your website had been deployed to. – Conor Gallagher Mar 10 '15 at 08:54
  • 1
    $"{System.Web.HttpContext.‌​Current.Request.Url.GetLeftPart(UriPartial.Authority)}{System.Web.HttpContext.Cur‌​rent.Request.ApplicationPath?.TrimEnd('/')}/"; – Ryan Penfold Sep 17 '15 at 07:03
  • Even though this answer has 362 votes, When Application is starting, `Request` does not exists generally on any routine that runs before any request arrive from user e.g. when code in Application_start or static class methods, handler registration code ... – AaA Jan 05 '23 at 02:48
176
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority)

That's it ;)

Warlock
  • 7,321
  • 10
  • 55
  • 75
  • 27
    This doesn't work for Virtual or Application Path. You should use Request.ApplicationPath in addition to the left part. – Warlock Aug 20 '13 at 19:58
  • base url is httpx://domain.com:[port]/ you must add app path yourself to this solution – Pawel Cioch Aug 17 '16 at 19:07
10

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);
Todd Menier
  • 37,557
  • 17
  • 150
  • 173
7

This is a much more fool proof method.

VirtualPathUtility.ToAbsolute("~/");
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
6

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.

cirrus
  • 5,624
  • 8
  • 44
  • 62
6

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('/') ;
rufo
  • 5,158
  • 2
  • 36
  • 47
4

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;
Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
SpazDude
  • 924
  • 1
  • 7
  • 11
4

I go with

HttpContext.Current.Request.ServerVariables["HTTP_HOST"]
Talha
  • 1,546
  • 17
  • 15
  • 1
    This will add the protocol: (HttpContext.Request.ServerVariables["HTTPS"] == "off" ? "http://" : "https://") + HttpContext.Request.ServerVariables["HTTP_HOST"] – onemorecupofcoffee Oct 20 '17 at 14:43
1

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

FAHID
  • 3,245
  • 3
  • 18
  • 15
1

I'm using following code from Application_Start

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

1

Please use the below code                           

string.Format("{0}://{1}", Request.url.Scheme, Request.url.Host);
Mohan Singh
  • 1,142
  • 3
  • 15
  • 30
-2

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?

Mark Redman
  • 24,079
  • 20
  • 92
  • 147