ASP.NET Core 中 ASP.NET Framework 的
HttpContext.Request.UserHostAddress
的等效项是什么?
我尝试了
this.ActionContext.HttpContext
但找不到 UserHostAddress
和 ServerVariables
属性。
如果您有权访问
HttpContext
,您可以从 Connection
属性获取本地/远程 IpAddress,如下所示:
var remote = this.HttpContext.Connection.RemoteIpAddress;
var local = this.HttpContext.Connection.LocalIpAddress;
自从 Badrinarayanan 在 2014 年的回答 发布以来,这已经发生了变化。立即通过
访问它httpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress
HttpRequest.UserHostAddress
给出远程客户端的IP地址。在 ASP.NET Core 1.0 中,您必须使用 HTTP 连接功能才能获得相同的效果。 HttpContext
有 GetFeature<T>
方法,您可以使用它来获取特定功能。例如,如果您想从控制器操作方法检索远程 IP 地址,您可以执行以下操作。
var connectionFeature = Context
.GetFeature<Microsoft.AspNet.HttpFeature.IHttpConnectionFeature>();
if (connectionFeature != null)
{
string ip = connectionFeature.RemoteIpAddress.ToString();
}
对于 ASP.NET Core RC1-update1,我在
X-Forwarded-For
标头中找到了 IP(带端口),其值可以从控制器访问为 HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault()
。