Thursday, October 28, 2021

Getting Geo Location free of charge.. in C# ASP.

 Sometimes we need to check the users geolocation from server side for various purposes. Such as link building for region wise. 

This is a free service that you can use for your application which isn't commercial.

you can browse more info here http://ip-api.com

lets see how we implement it.


 string jsonCountry = Session["country"] != null ? Session["country"].ToString() : string.Empty;  
         if (!string.IsNullOrEmpty(jsonCountry))  
         {  
           location = new JavaScriptSerializer().Deserialize<Location>(jsonCountry);  
         }  
         else  
         {  
           string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
           if (string.IsNullOrEmpty(ipAddress))  
           {  
             ipAddress = Request.ServerVariables["REMOTE_ADDR"];  
           }  
           string urlLocation = "http://ip-api.com/json/" + ipAddress;  
           using (WebClient client = new WebClient())  
           {   
             string json = client.DownloadString(urlLocation);  
             Session["country"] = json;  
             location = new JavaScriptSerializer().Deserialize<Location>(json);              
           }  
         }  


Here you can see we use session to store location data to prevent unwanted http calls to the service provider. Location is a class that we use to deserialize the object.

   public class Location  
   {  
     public string status { get; set; }  
     public string country { get; set; }  
     public string countryCode { get; set; }  
     public string region { get; set; }  
     public string regionName { get; set; }  
     public string city { get; set; }  
     public string zip { get; set; }  
     public double lat { get; set; }  
     public double lon { get; set; }  
     public string timezone { get; set; }  
     public string isp { get; set; }  
     public string org { get; set; }  
     public string @as { get; set; }  
     public string query { get; set; }  
   }  

If you want you can add a proxy to your webclient as below

             WebProxy wp = new WebProxy();
             wp.Address = new Uri(string.Format("{0}:{1}", "http://proxy.something.io", "22222"));  
             wp.Credentials = new NetworkCredential("username", "password");  
             client.Proxy = wp;  

Hopefully this works.

Happy coding.