ASP.NET Core 中的 UserHostAddress 相当于什么?

问题描述 投票:0回答:4

ASP.NET Core 中 ASP.NET Framework 的

HttpContext.Request.UserHostAddress
的等效项是什么?

我尝试了

this.ActionContext.HttpContext
但找不到
UserHostAddress
ServerVariables
属性。

asp.net-core httpcontext
4个回答
59
投票

如果您有权访问

HttpContext
,您可以从
Connection
属性获取本地/远程 IpAddress,如下所示:

var remote = this.HttpContext.Connection.RemoteIpAddress;
var local = this.HttpContext.Connection.LocalIpAddress;

20
投票

自从 Badrinarayanan 在 2014 年的回答 发布以来,这已经发生了变化。立即通过

访问它
httpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress

16
投票

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

0
投票

对于 ASP.NET Core RC1-update1,我在

X-Forwarded-For
标头中找到了 IP(带端口),其值可以从控制器访问为
HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault()

© www.soinside.com 2019 - 2024. All rights reserved.