首页 > 解决方案 > 访问我的网站时如何获取客户端 IP 地址?

问题描述

我使用 dotnet core 3.1,我需要网站访问者的 IP 地址,但是当我尝试获取它时,返回的是服务器的 IP,而不是客户端。这是我使用的代码:

var ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

这将返回 null。然后我尝试使用第三方网站获取我的 IP 地址。所以我这样做了:

WebRequest request = WebRequest.Create("https://api.ipify.org/");

这也将返回服务器的 IP 地址,而不是客户端。然后我尝试了这个:

var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
    if (ip.AddressFamily == AddressFamily.InterNetwork)
    {
        return ip.ToString();
    }
}

和这个:

string localIP = string.Empty;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
    socket.Connect("8.8.8.8", 65530);
    IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
    localIP = endPoint.Address.ToString();
}

但它们返回本地 IP 地址。返回本地IP.ToString();

并且某些代码行HTTPContext.Current.Request.UserHostAddressServerVariables["REMOTE_ADDR"]在 dotnet 核心中无效。请问有什么建议吗?

标签: c#asp.net-mvcasp.net-core

解决方案


I'm assuming that you are running the website not by directly exposing Kesterl to the end clients but under some reverse proxy (IIS/nginx). In that case for Connection.RemoteIpAddress to work property you have to configure the application by adding something like following code in the startup:

app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor })

推荐阅读