从用户获取IP地址

时间:2014-04-07 21:57:48

标签: c# xml asp.net-mvc api

我正在对IP地址进行硬编码以进行测试,如下所示。

string country = GetCountryByIP("173.194.113.23"); 

现在这里是我的GetCountryByIP方法,其中输入了ip地址:

    public string GetCountryByIP(string ipAddress)
    {
        string ipResponse = IPRequestHelper("http://api.ipinfodb.com/v3/ip-country/?key=(api key deleted for security purposes)&ip=", ipAddress);

        XmlDocument ipInfoXML = new XmlDocument();
        ipInfoXML.LoadXml(ipResponse);
        XmlNodeList responseXML = ipInfoXML.GetElementsByTagName("Response");

        NameValueCollection dataXML = new NameValueCollection();

        dataXML.Add(responseXML.Item(0).ChildNodes[2].InnerText, responseXML.Item(0).ChildNodes[2].Value);

        string xmlValue = dataXML.Keys[0];

        return xmlValue;
    }

我的IP帮助来自api:

    public string IPRequestHelper(string url, string ipAddress)
    {
        string checkURL = url + ipAddress;

        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();

        StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
        string responseRead = responseStream.ReadToEnd();

        responseStream.Close();
        responseStream.Dispose();

        return responseRead;
    }

我从xml中的api得到响应,说它是一个无效的ip地址。在调试模式下,url和ip地址正确地传递到两个方法中的参数中。我在浏览器的地址栏中测试了正确的url和ip地址(硬编码),它运行正常。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

想出来,对不起伙计们。写的地方:

    string checkURL = url + ipAddress;

    HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);

问题在于:

    HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(checkUrl);
                                                                  ^^^^^^^^