ASP.NET 中获取当前域的最佳方法是什么?

我想知道在 ASP.NET 中获得当前域名的最佳方法是什么?

例如:

Http://www.domainname.com/subdir/应该会产生 http://www.domainname.com Http://www.sub.domainname.com/subdir/应该会产生一个 http://sub.domainname.com

作为一个指南,我应该能够添加一个像“/Folder/Content/filename.html”这样的 URL (例如由 Url 生成的。NET MVC 中的 RouteUrl ()直接连接到 URL 上,应该可以工作。

95198 次浏览

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:

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

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

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}"

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.

Why not use

Request.Url.Authority

It returns the whole domain AND the port.

You still need to figure http or https

Request.Url.GetLeftPart(UriPartial.Authority)

This is included scheme.

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

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

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