Get user location by IP address

前端 未结 14 1141
深忆病人
深忆病人 2020-11-28 02:23

I have an ASP.NET website written in C#.

On this site I need to automatically show a start page based on the user\'s location.

Can I get name of user\'s city

相关标签:
14条回答
  • 2020-11-28 03:00

    Using the Request of following web site

    http://ip-api.com/

    Following is C# code for returning Country and Country Code

    public  string GetCountryByIP(string ipAddress)
        {
            string strReturnVal;
            string ipResponse = IPRequestHelper("http://ip-api.com/xml/" + ipAddress);
    
            //return ipResponse;
            XmlDocument ipInfoXML = new XmlDocument();
            ipInfoXML.LoadXml(ipResponse);
            XmlNodeList responseXML = ipInfoXML.GetElementsByTagName("query");
    
            NameValueCollection dataXML = new NameValueCollection();
    
            dataXML.Add(responseXML.Item(0).ChildNodes[2].InnerText, responseXML.Item(0).ChildNodes[2].Value);
    
            strReturnVal = responseXML.Item(0).ChildNodes[1].InnerText.ToString(); // Contry
            strReturnVal += "(" + 
    
    responseXML.Item(0).ChildNodes[2].InnerText.ToString() + ")";  // Contry Code 
     return strReturnVal;
    }
    

    And following is Helper for requesting url.

    public string IPRequestHelper(string url) {
    
          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;
    }
    
    0 讨论(0)
  • 2020-11-28 03:00

    Return country

    static public string GetCountry()
    {
        return new WebClient().DownloadString("http://api.hostip.info/country.php");
    }
    

    Usage:

    Console.WriteLine(GetCountry()); // will return short code for your country
    

    Return info

    static public string GetInfo()
    {
        return new WebClient().DownloadString("http://api.hostip.info/get_json.php");
    }
    

    Usage:

    Console.WriteLine(GetInfo()); 
    // Example:
    // {
    //    "country_name":"COUNTRY NAME",
    //    "country_code":"COUNTRY CODE",
    //    "city":"City",
    //    "ip":"XX.XXX.XX.XXX"
    // }
    
    0 讨论(0)
提交回复
热议问题