What's the best method in ASP.NET to obtain the current domain?

Viewed 94914
11 Answers

As per this link a good starting point is:

Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host 

However, if the domain is http://www.domainname.com:500 this will fail.

Something like the following is tempting to resolve this:

int defaultPort = Request.IsSecureConnection ? 443 : 80;
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host 
  + (Request.Url.Port != defaultPort ? ":" + Request.Url.Port : "");

However, port 80 and 443 will depend on configuration.

As such, you should use IsDefaultPort as in the Accepted Answer above from Carlos Muñoz.

How about:

NameValueCollection vars = HttpContext.Current.Request.ServerVariables;
string protocol = vars["SERVER_PORT_SECURE"] == "1" ? "https://" : "http://";
string domain = vars["SERVER_NAME"];
string port = vars["SERVER_PORT"];

Another way:


string domain;
Uri url = HttpContext.Current.Request.Url;
domain= url.AbsoluteUri.Replace(url.PathAndQuery, string.Empty);

In Asp.Net Core 3.1 if you want to get a full domain, here is what you need to do:

Step 1: Define variable

private readonly IHttpContextAccessor _contextAccessor;

Step 2: DI into the constructor

public SomeClass(IHttpContextAccessor contextAccessor)
{
    _contextAccessor = contextAccessor;
}

Step 3: Add this method in your class:

private string GenerateFullDomain()
{
    string domain = _contextAccessor.HttpContext.Request.Host.Value;
    string scheme = _contextAccessor.HttpContext.Request.Scheme;
    string delimiter = System.Uri.SchemeDelimiter;
    string fullDomainToUse = scheme + delimiter + domain;
    return fullDomainToUse;
}
//Examples of usage GenerateFullDomain() method:
//https://example.com:5031
//http://example.com:5031

How about:

String domain = "http://" + Request.Url.Host
Related