Tuesday, April 20, 2021

To get country/geo location of a user using C# MVC, client IP

 If you would like to know the geo location of the client who is visiting your website or to show some specific content based on visitor country/location then this article helps you.

To know the country name, we need to get the IP address of the user and check with the Geo location database to get the location/country based on the IP address. The geo location database is available with many geo location providers. Either we can run that instance in our own server or call the geo location provider API to get the location details.

Note: All the Geolocation providers get the location details based on the IP address. So if the user if spoofing his IP address, then we might get a different location.

Although there are many geo location providers in the market, in this example we will consider the ip2location.com API to get the geolocation. ip2location.com provides a free plan as well with limited credits of 5k queries. If you think you might send more requests then check their pricing and get a suitable plan for you.

Steps

1. Getting the client IP address.

Use the below code to get the client IP address. i.e., the IP address of the machine which requested a page in your website.

String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
    UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}

2. Calling the Geo IP Service/API

Below is the format we need to use for the API URL.

https://api.ip2location.com/v2/?ip={IP_address}&key=demo&package=WS2&addon=continent

key –> this is the secret access key provided by ip2Location when we signup with them for an account (both free and premium). They also provide a demo key with limit of 20 requests per day, hence I used it in this example.

For example, if we like to get the location details with IP address then we could use the API URL as 'https://api.ip2location.com/v2/?ip=49.206.33.84&key=demo&package=WS2&addon=continent'

string url = "https://api.ip2location.com/v2/?ip=" + UserIP.ToString() + "&key=" + AccessKey.ToString() + "&package=WS2&addon=continent";
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);

3. Reading the Geo location details from the response.

To get the sample response format, run this "https://api.ip2location.com/v2/?ip=2607:f1c0:100f:f000::2f4&key=demo&package=WS2&addon=continent,country" (replace 'demo' with access key) URL directly in the browser. You will see the below response format.

{"country_code":"US","country_name":"United States of America","isp":"1&1 IONOS Inc.","credits_consumed":5,"continent":{"name":"North America","code":"NA","hemisphere":["north","west"],"translations":[]},"country":{"name":"United States of America","alpha3_code":"USA","numeric_code":"840","demonym":"Americans","flag":"https:\/\/cdn.ip2location.com\/assets\/img\/flags\/us.png","capital":"Washington, D.C.","total_area":"9826675","population":"326766748","currency":{"code":"USD","name":"United States Dollar","symbol":"$"},"language":{"code":"EN","name":"English"},"idd_code":"1","tld":"us","translations":[]}}

I have used the Advanced REST client to make the GET request, but instead you can even directly try it from browser.

Getting location details using geoip

Use the below code to convert the response to JSON object and then read the values of JSON object and save to a session variable or some other variable.

dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["LocId"] = dynObj.country_code;

Final Code

String AccessKey = "";
String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
    UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}

string url = "https://api.ip2location.com/v2/?ip=" + UserIP.ToString() + "&key=" + AccessKey.ToString() + "&package=WS2&addon=continent";
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;

No comments:

Post a Comment