NET Core中如何通过用户IP地址获取国家/地区?

问题描述

我想通过他的IP获取登录用户的国家。第一个功能获取IP地址。

.swiper-container {
    width:100%;
    height:auto;
}
.swiper-slide {
    width:auto;
    height:auto;
}
.swiper-container img {
    width:100%;
    height:auto;
}

第二个功能使用ip并返回国家/地区

 public static string GetLocalIPAddress()
 {
    var host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            return ip.ToString();
        }
    }
    throw new Exception("No network adapters with an IPv4 address in the system!");
}

这里的问题是第二个函数不返回任何数据。当我在https://ipinfo.io/IP尝试IP时,它返回bogon = true。

我怎么不退回Bogon ip。

解决方法

如果要获取客户端的IP地址,则需要使用客户端的IP地址而不是主机。要在ASP.Net Core中执行此操作,可以执行以下操作:

var clientIpAddress = request.HttpContext.Connection.RemoteIpAddress;

从那里,您可以将clientIpAddress用作传递给GetUserCountryByIp函数的IP。