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

I am wondering what the best way to obtain the current domain is in ASP.NET?

For instance:

http://www.domainname.com/subdir/ should yield http://www.domainname.com
http://www.sub.domainname.com/subdir/ should yield http://sub.domainname.com

As a guide, I should be able to add a url like “/Folder/Content/filename.html” (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Same answer as MattMitchell’s but with some modification.
This checks for the default port instead.

Edit: Updated syntax and using Request.Url.Authority as suggested

$"{Request.Url.Scheme}{System.Uri.SchemeDelimiter}{Request.Url.Authority}"

Method 2

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.

Method 3

Request.Url.GetLeftPart(UriPartial.Authority)

This is included scheme.

Method 4

WARNING! To anyone who uses Current.Request.Url.Host. Understand that you are working based on the CURRENT REQUEST and that the current request will not ALWAYS be with your server and can sometimes be with other servers.

So if you use this in something like, Application_BeginRequest() in Global.asax, then 99.9% of the time it will be fine, but 0.1% you might get something other than your own server’s host name.

A good example of this is something I discovered not long ago. My server tends to hit http://proxyjudge1.proxyfire.net/fastenv from time to time. Application_BeginRequest() gladly handles this request so if you call Request.Url.Host when it’s making this request you’ll get back proxyjudge1.proxyfire.net. Some of you might be thinking “no duh” but worth noting because it was a very hard bug to notice since it only happened 0.1% of the time : P

This bug has forced me to insert my domain host as a string in the config files.

Method 5

Why not use

Request.Url.Authority

It returns the whole domain AND the port.

You still need to figure http or https

Method 6

Simple and short way (it support schema, domain and port):

Use Request.GetFullDomain()

// Add this class to your project
public static class HttpRequestExtensions{
    public static string GetFullDomain(this HttpRequestBase request)
    {
        var uri= request?.UrlReferrer;
        if (uri== null)
            return string.Empty;
        return uri.Scheme + Uri.SchemeDelimiter + uri.Authority;
    }
}

// Now Use it like this:
Request.GetFullDomain();
// Example output:    https://example.com:5031
// Example output:    http://example.com:5031

Method 7

Another way:

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

Method 8

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"];

Method 9

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

Method 10

Using UriBuilder:

    var relativePath = ""; // or whatever-path-you-want
    var uriBuilder = new UriBuilder
    {
        Host = Request.Url.Host,
        Path = relativePath,
        Scheme = Request.Url.Scheme
    };

    if (!Request.Url.IsDefaultPort)
        uriBuilder.Port = Request.Url.Port;

    var fullPathToUse = uriBuilder.ToString();

Method 11

How about:

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x