2016-09-24 83 views
0

我使用名为GeoIP的.net服务,我有一个例外让我失望。.NET异常的GeoIP服务

服务地址:http://www.webservicex.net/geoipservice.asmx?WSDL

我用它第一次,所以它可能似乎是“点击和手表”的代码,但不是最主要的。

我有一个例外,当我试图获得一个IO或国家initalizing客户端后。

 GeoIPService.GeoIP geoIp; 
     GeoIPServiceSoapClient client; 
     client = new GeoIPServiceSoapClient("GeoIPServiceSoap"); 

     geoIp = client.GetGeoIP("37.57.106.53"); // HERE IS EXCEPTION 

异常消息文本:

类型 'System.ServiceModel.FaultException' 的未处理的异常出现在mscorlib.dll

其他信息:服务器无法处理服务器无法处理请求。 ---> System.NullReferenceException:未将对象引用设置为对象的实例。

在WebserviceX.Service.Adapter.IPAdapter.CheckIP(字符串IP)

在WebserviceX.Service.GeoIPService.GetGeoIP(字符串的IPAddress)

---内部异常堆栈跟踪的结尾---

而且还有一个链接,PRINTSCREEN:https://www.dropbox.com/s/yoq1pr7zp6qax04/geoIpEx.png?dl=0

这将是对我真的很幸运,如果有人要使用这项服务,并知道如何解决这个麻烦。

谢谢!

+1

'我有一个例外,这让我dissapointed'好措辞,但服务似乎没有回答您的请求。看看用户友好的网站'http://www.webservicex.net/geoipservice.asmx?op = GetGeoIP'并输入IP地址'37.57.1​​06.53',你会发现**服务器**也有问题。在你身边不是问题,但Web服务被破坏。当我输入我的IP地址时,它可以正常工作 - 所以它可能只是服务器不能解析**这个特定的地址,你运气不好。 –

+0

@MaximilianGerhardt Hmgh,你是对的。我输入了一些美国IP地址,然后geoip服务向我显示该国家。作为一个主要问题,没有例外。您在此处链接的Web站点(http://www.webservicex.net/geoipservice.asmx?op=GetGeoIP) - 我使用的是服务的附加服务吗? (对不起,重言式) –

+0

不,这不是一个单独的服务,它是不同的绑定完全相同的服务。查看POST示例,POST /geoipservice.asmx HTTP/1.1',或者使用GET GET /geoipservice.asmx/GetGeoIP?IPAddress=string',它将访问完全相同的网站。 Google也有GeoIP服务,还有数百万人。首先谷歌命中给我'https:// freegeoip.net/json/37.57.1​​06.53'。 –

回答

1

根据注释,需要不同的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; } 
} 

我们下载JSON通过HTTP与WebClient对象,然后将字符串转换成使用Newtonsoft.JSON以上C#对象。 (通过nuget包在https://www.nuget.org/packages/Newtonsoft.Json/安装库文件)。样本程序是:

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. 
+0

非常感谢你! –