【发布时间】:2016-03-24 03:37:04
【问题描述】:
我成功地使用 MaxMind GeoIP Legacy .NET API (https://github.com/maxmind/geoip-api-csharp2) Country Class 根据 IP 检索国家代码。但是,我在尝试使用 Location 类时遇到了问题。以下是我的代码:
try
{
// capture visitors IP
string visitorIp = Model.ServerVariables["HTTP_X_Forwarded_For"];
visitorIp = String.IsNullOrWhiteSpace(visitorIp) ? Request.UserHostAddress : visitorIp;
string geoIpPath = HttpContext.Current.Server.MapPath("~/App_Data/GeoIP.dat");
LookupService ls = new LookupService(geoIpPath, LookupService.GEOIP_MEMORY_CACHE);
//get country of the ip address
Country c = ls.getCountry(visitorIp);
string countryCode = c.getCode() != "--" ? c.getCode() : "US";
// Capture country code as cookie
if (Request.Cookies["GeoIP"] == null)
{
HttpCookie cookie = new HttpCookie("GeoIP", countryCode);
cookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookie);
}
string geoIpCityPath = HttpContext.Current.Server.MapPath("~/App_Data/GeoLiteCity.dat");
LookupService lsCity = new LookupService(geoIpCityPath, LookupService.GEOIP_MEMORY_CACHE);
Location l = ls.getLocation(visitorIp);
<h1>Postal Code = @l.postalCode.ToString()</h1>
}
catch (Exception e)
{
<p>@e</p>
}
字符串 countryCode 被正确跟踪。当我尝试使用 Location 类时,我收到以下错误消息:
System.ArgumentOutOfRangeException:需要非负数。 参数名称:长度在 System.Array.Copy(Array sourceArray, Int32 sourceIndex,数组destinationArray,Int32destinationIndex,Int32 System.Array.Copy(Array sourceArray, Int32 sourceIndex,数组destinationArray,Int32destinationIndex, Int32 长度)在 LookupService.getLocation(Int64 ipnum) 中 ~\Models\LookupService.cs:行 582 在 LookupService.getLocation(IPAddress addr) 中 ~\Models\LookupService.cs:行 443 在 ASP._Page_Views_Shared__GeoIP_cshtml.Execute() 中 ~\Views\Shared_GeoIP.cshtml:第 34 行
想法?提前致谢!
【问题讨论】:
-
您使用旧版 API 而不是 GeoIP2 API 是否有原因?前者一般来说有点乱。
-
@oschwald 我正在与之集成的项目仍在 .Net 4.0 上,因此目前可能无法选择较新的版本(希望不是这种情况)。
-
如果您确实想使用 GeoIP2 API,您可以使用 2.4.0,这是支持 .NET 4.0 的最后一个版本。
-
至于你上面的问题,你使用的是NuGet的关闭版本吗?这是由第三方完成的,我认为它已经过时并且可能缺少某些国家/地区,这可能导致上述问题。您是否在所有 IP 上都获得了它?
-
@oschwald 如何获得 GeoIP2 API v2.4.0?至于 Legacy API,我相信它是直接从 Github 而不是 nuget 获得的。我将对各种 IP 进行更多测试,但到目前为止,我尝试过的所有方法似乎都出错了。顺便说一句,感谢您的所有输入!
标签: c# asp.net .net geoip maxmind