我想在asp.net c#中获取当前域名.
我正在使用此代码.
string DomainName = HttpContext.Current.Request.Url.Host;
Run Code Online (Sandbox Code Playgroud)
我的网址是,localhost:5858但它只是返回localhost.
现在,我在localhost中使用我的项目.我想得到localhost:5858.
再举一个例子,当我使用这个域名时
www.somedomainname.com
Run Code Online (Sandbox Code Playgroud)
我想得到 somedomainname.com
请告诉我如何获取当前域名.
Art*_*hez 77
尝试获取网址的"左侧部分",如下所示:
string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
Run Code Online (Sandbox Code Playgroud)
这会给你要么http://localhost:5858或者https://www.somedomainname.com无论你是在本地或生产.如果要删除该www部件,则应配置IIS以执行此操作,但这是另一个主题.
请注意,生成的URL不会有尾部斜杠.
Dai*_*Dai 62
使用Request.Url.Host是合适的 - 它是如何检索HTTP Host:标头的值,它指定UA(浏览器)想要的主机名(域名),因为HTTP请求的资源路径部分不包括主机名.
请注意,localhost:5858它不是域名,它是端点说明符,也称为"权限",包括主机名和TCP端口号.这是通过访问来检索的Request.Uri.Authority.
此外,它是不是有效的获得somedomain.com来自www.somedomain.com因为网络服务器可以被配置为服务于不同的网站www.somedomain.com相比somedomain.com,但是如果你确定这是你的情况下,有效的,那么你需要手动解析主机名,但使用String.Split('.')的作品紧要关头.
请注意,Web服务器(IIS)配置与ASP.NET的配置不同,并且ASP.NET实际上完全不知道它运行的网站和Web应用程序的HTTP绑定配置.IIS和ASP.NET共享相同的配置文件(web.config)的事实是一个红鲱鱼.
Raj*_*hta 16
您可以尝试以下代码:
Request.Url.Host +
(Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)
Run Code Online (Sandbox Code Playgroud)
小智 12
我在asp.net core 3.1中这样使用它
var url =Request.Scheme+"://"+ Request.Host.Value;
Run Code Online (Sandbox Code Playgroud)
www.somedomain.com 是域/主机.子域是一个重要的部分.www.通常可以互换地使用,但是必须将其设置为规则(即使它是默认设置),因为它们不相同.想想另一个子域,比如mx..这可能与目标不同www..
鉴于此,我建议不要做这种事情.那就是说,因为你问我想你有充分的理由.
就个人而言,我建议使用特殊套管www..
string host = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);;
if (host.StartsWith("www."))
return host.Substring(4);
else
return host;
Run Code Online (Sandbox Code Playgroud)
否则,如果您真的100%确定要切断任何子域,那么您将需要更复杂的东西.
string host = ...;
int lastDot = host.LastIndexOf('.');
int secondToLastDot = host.Substring(0, lastDot).LastIndexOf('.');
if (secondToLastDot > -1)
return host.Substring(secondToLastDot + 1);
else
return host;
Run Code Online (Sandbox Code Playgroud)
获得端口就像其他人说的那样.