Get user location by IP address

前端 未结 14 1285
深忆病人
深忆病人 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 02:54

    Use http://ipinfo.io , You need to pay them if you make more than 1000 requests per day.

    The code below requires the Json.NET package.

    public static string GetUserCountryByIp(string ip)
    {
        IpInfo ipInfo = new IpInfo();
        try
        {
            string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
            ipInfo = JsonConvert.DeserializeObject(info);
            RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
            ipInfo.Country = myRI1.EnglishName;
        }
        catch (Exception)
        {
            ipInfo.Country = null;
        }
        
        return ipInfo.Country;
    }
    

    And the IpInfo Class I used:

    public class IpInfo
    {
        [JsonProperty("ip")]
        public string Ip { get; set; }
    
        [JsonProperty("hostname")]
        public string Hostname { get; set; }
    
        [JsonProperty("city")]
        public string City { get; set; }
    
        [JsonProperty("region")]
        public string Region { get; set; }
    
        [JsonProperty("country")]
        public string Country { get; set; }
    
        [JsonProperty("loc")]
        public string Loc { get; set; }
    
        [JsonProperty("org")]
        public string Org { get; set; }
    
        [JsonProperty("postal")]
        public string Postal { get; set; }
    }
    

提交回复
热议问题