Get user location by IP address

前端 未结 14 1244
深忆病人
深忆病人 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:41

    I was able to achieve this in ASP.NET MVC using the client IP address and freegeoip.net API. freegeoip.net is free and does not require any license.

    Below is the sample code I used.

    String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (string.IsNullOrEmpty(UserIP))
    {
        UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    }
    string url = "http://freegeoip.net/json/" + UserIP.ToString();
    WebClient client = new WebClient();
    string jsonstring = client.DownloadString(url);
    dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
    System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;
    

    You can go through this post for more details.Hope it helps!

提交回复
热议问题