[英]GeoIP Service for .NET Exception
我使用名为GeoIP的.net服务,但有一个使我失望的异常。
服务地址: http : //www.webservicex.net/geoipservice.asmx?WSDL
我是第一次使用它,因此它似乎是“单击并监视”代码,但这并不是主要内容。
初始化客户后尝试获取IO或国家/地区时,我有一个例外。
GeoIPService.GeoIP geoIp;
GeoIPServiceSoapClient client;
client = new GeoIPServiceSoapClient("GeoIPServiceSoap");
geoIp = client.GetGeoIP("37.57.106.53"); // HERE IS EXCEPTION
异常消息文本:
mscorlib.dll中发生了类型为'System.ServiceModel.FaultException'的未处理异常
附加信息:System.Web.Services.Protocols.SoapException:服务器无法处理请求。 ---> System.NullReferenceException:对象引用未设置为对象的实例。
在WebserviceX.Service.Adapter.IPAdapter.CheckIP(String IP)
在WebserviceX.Service.GeoIPService.GetGeoIP(String IPAddress)
---内部异常堆栈跟踪的结尾---
并且有一个用于打印屏幕的链接: https ://www.dropbox.com/s/yoq1pr7zp6qax04/geoIpEx.png ? dl =0
如果有人必须使用此服务并且知道如何解决该问题,对我来说真的很幸运。
谢谢!
根据评论,需要一个不同的GeoIP提供程序,因为它不能很好地解析所有主机地址。
我们可以使用http://json2csharp.com/并从该IP地址向其提供JSON。 生成C#类:
public class GeoIPInfo
{
public string ip { get; set; }
public string country_code { get; set; }
public string country_name { get; set; }
public string region_code { get; set; }
public string region_name { get; set; }
public string city { get; set; }
public string zip_code { get; set; }
public string time_zone { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public int metro_code { get; set; }
}
我们使用WebClient
对象通过HTTP下载JSON,然后使用Newtonsoft.JSON
将字符串转换为上述C#对象。 (通过nuget软件包(位于https://www.nuget.org/packages/Newtonsoft.Json/ )安装libary)。 一个示例程序将是:
static void Main(string[] args)
{
/* Download the string */
WebClient client = new WebClient();
string json = client.DownloadString("https://freegeoip.net/json/37.57.106.53");
Console.WriteLine("Returned " + json);
/* We deserialize the string into our custom C# object. ToDo: Check for null return or exception. */
var geoIPInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<GeoIPInfo>(json);
/* Print out some info */
Console.WriteLine(
"We resolved the IP {0} to country {1}, which has the timezone {2}.",
geoIPInfo.ip, geoIPInfo.country_name, geoIPInfo.time_zone);
Console.ReadLine();
return;
}
哪个输出
We resolved the IP 37.57.106.53 to country Ukraine, which has the timezone Europe/Kiev.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.