ip2location facebbook  ip2location twitter  ip2location google+

Display Visitor's GeoLocation Using Web Service in C#

Geolocation is a great way to put relevant content to your web visitors and it is a technology that can be used in almost any application you can think of.

In this tutorial, we use the IP2Location™ Web Service to lookup geolocation information from the visitor's IP address. Instead of loading the full database, you can also lookup IP address via our hosted web service.

Below are the sample codes written in C# to query and display user's geolocation information.

			public partial class _Default : System.Web.UI.Page
			{
				protected void Page_Load(object sender, EventArgs e)
				{
					WebAPI();
				}
				
				private void WebAPI()
				{
					string myIP = HttpContext.Current.Request.UserHostAddress;
					string strQuery;
					string key = "demo";
					HttpWebRequest HttpWReq;
					HttpWebResponse HttpWResp;
					strQuery = "http://api.ip2location.com/?" + "ip=" + myIP + "&key=" + key + "&package=WS24&format=json";
					JavaScriptSerializer serializer = new JavaScriptSerializer();
					
					HttpWReq = (HttpWebRequest)WebRequest.Create(strQuery);
					HttpWReq.Method = "GET";
					HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
					System.IO.StreamReader reader = new System.IO.StreamReader(HttpWResp.GetResponseStream());
					string content = reader.ReadToEnd();
					dynamic item = serializer.Deserialize<object>(content);
					string city = item["city_name"];
					string countryc = item["country_code"];
					string countryn = item["country_name"];
					string region = item["region_name"];
					string lat = item["latitude"];
					string longi = item["longitude"];
					string timez = item["time_zone"];
					string zip = item["zip_code"];
					
					//displaying the result
					Response.Write("Welcome Visitors from " + city + "<br />");
					Response.Write("Your IP address: " + myIP + "<br />");
					Response.Write("Country Code: " + countryc + "<br />");
					Response.Write("Country Name: " + countryn + "<br />");
					Response.Write("Region Name: " + region + "<br />");
					Response.Write("Latitude: " + lat + "<br />");
					Response.Write("Longitude: " + longi + "<br />");
					Response.Write("Time Zone: " + timez + "<br />");
					Response.Write("Zip Code: " + zip + "<br />");
				}
				
			}
			

 


Do you like this article? Share it with others by clicking the social media buttons below. We will write more articles related to this topic.