2016-09-24 64 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

非常感謝你! –