如何在ASP.NET Core 2.1中获取客户端IP地址

Ahm*_*san 22 c# asp.net-core

我正在使用Microsoft Visual Studio 2017提供的Angular模板开发ASP.Net Core 2.1.我的客户端应用程序工作正常.在用户认证竞争之后,我想启动用户会话管理,其中我存储客户端用户IP地址.我已经在互联网上搜索过这个,但到目前为止还没有找到任何解决方案.

以下是我访问过的一些参考链接:

如何在ASP.NET CORE中获取客户端IP地址?

在ASP.NET Core 2.0中获取客户端IP地址

在ASP.Net Core中获取用户远程IP地址

在我的ValuesController.cs中,我也试过下面的代码:

private IHttpContextAccessor _accessor;

public ValuesController(IHttpContextAccessor accessor)
{
    _accessor = accessor;
}

public IEnumerable<string> Get()
{
    var ip = Request.HttpContext.Connection.RemoteIpAddress.ToString();
    return new string[] { ip, "value2" };
}
Run Code Online (Sandbox Code Playgroud)

其中ip变量我得到空值并得到此错误

Request.HttpContext.Connection.RemoteIpAddress.Address引发了Type'System.Net.Sockets.SocketException'的异常

在此输入图像描述

在此输入图像描述

你能告诉我如何在ASP.NET Core 2.1中获取客户端IP地址吗?

zdu*_*dub 12

在你的Startup.cs,确保你有一个方法来ConfigureServices,传入IServiceCollection,然后注册IHttpContextAccessor为单身,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
Run Code Online (Sandbox Code Playgroud)

IHttpContextAccessor在您的Startup.cs文件中注册后,您可以IHttpContextAccessor在控制器类中注入并使用它,如下所示:

private IHttpContextAccessor _accessor;

public ValuesController(IHttpContextAccessor accessor)
{
    _accessor = accessor;
}

public IEnumerable<string> Get()
{
    var ip = _accessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
    return new string[] { ip, "value2" };
}
Run Code Online (Sandbox Code Playgroud)

  • 在本地计算机上运行时,ToString的值对我来说是“ :: 1”。 (4认同)

小智 9

可以使用以下代码:

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

string remoteIpAddress = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
if (Request.Headers.ContainsKey("X-Forwarded-For"))
    remoteIpAddress = Request.Headers["X-Forwarded-For"];
Run Code Online (Sandbox Code Playgroud)


Yus*_*sh0 6

如果您的 Kestrel 位于像 IIS 这样的反向代理后面,请确保转发包含客户端 IP 的标头。
这进入启动:

app.UseForwardedHeaders(new ForwardedHeadersOptions{ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto});
Run Code Online (Sandbox Code Playgroud)


Ahm*_*san -3

花了一些时间搜索后,我找到了自己的问题答案。在这里,我还分享了源链接,从中我可以获得答案和详细说明,了解如何查询服务器以获取家庭地址及其支持的 IP 地址。

代码:

IPHostEntry heserver = Dns.GetHostEntry(Dns.GetHostName());
var ip = heserver.AddressList[2].ToString();
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

来源

这是我的另一个问题:如何访问 ASP.Net Core 2.x 中的服务器变量希望这对大家有所帮助。

  • 我不确定是否明白。这很有趣,但在我看来,您的答案并没有给出正在查询您的服务器的客户端的*客户端* IP 地址,这就是您的问题。 (3认同)