【发布时间】:2020-10-08 17:43:15
【问题描述】:
我想通过他的 IP 获取登录用户的国家。第一个函数获取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!");
}
第二个函数获取ip并返回国家
public static string GetUserCountryByIp(string ip)
{
IpInfo ipInfo = new IpInfo();
try
{
string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
ipInfo.Country = myRI1.EnglishName;
}
catch (Exception)
{
ipInfo.Country = null;
}
return ipInfo.Country;
}
这里的问题是第二个函数没有返回任何数据。当我在https://ipinfo.io/IP 尝试我的 IP 时,它返回 bogon=true 。
我怎样才能返回不 bogon ip。
【问题讨论】:
-
从标签看来,您是在 ASP.NET 中运行该代码。除了您已经知道的位置之外,您希望您的服务器区域是什么?
-
我需要返回 IP 的函数,我可以从该 IP 获取所有数据(国家、城市)
-
你需要的是用户的IP,而不是你服务器的IP。请edit 您的问题,并删除.net-core 标记(如果您使用的是ASP.NET)或更改asp.net 标记为asp.net-core 标记(如果您使用的是ASP.NET Core)。
标签: c# asp.net-mvc algorithm .net-core asp.net-core-mvc