find and solve || findandsolve.com
Please wait.....

User GeoLocation in ASP.NET Core

User GeoLocation in ASP.NET Core


Geolocation is allowed the current user their location to the web application if they so desire. In a different situation, the web application required Geolocation, IP address, or many more from the client or server site.

This blog will help to get all user details from the server site using c#. Like country code, longitude, latitude, country name, region name, city, zip code many more using asp.net core. Need to requests a page from your site the request object provides the IP address of the user and this IP address can be used to look up their approximate location using a free service such as freegeoip.net.(now ipstack). 


Usage


I want to use the ipstack this is very simple for me. All you need to do is issue an HTTP GET request passing the IP address in the URL.

Providing user details from API as given below which provide zip code, country name, region name, country code, geolocation, etc.

"http://api.ipstack.com/<MyIPAddress>?access_key=<Key>"


<Key>: I have gotten a key from https://ipstack.com/ (Click on the Get Free API Key button) by signup.

< MyIPAddress >: I have to get my IP address from https://ipinfo.io/IP.


I am going to create a function in .net core and get my IP address.

public class GeoInfoProvider
{
     private readonly HttpClient _httpClient;
     //create constructor and call HttpClient
     public GeoInfoProvider()
     {
        _httpClient = new HttpClient()
         {
           Timeout = TimeSpan.FromSeconds(5)
         };
    }
    private async Task<string> GetIPAddress()
    {
      var ipAddress = await _httpClient.GetAsync($"http://ipinfo.io/ip");
      if (ipAddress.IsSuccessStatusCode)
      {
        var json = await ipAddress.Content.ReadAsStringAsync();
        return json.ToString();
      }
      return "";
    }
}


Calling the API from .NET Core


I have got my Ipaddress as given above function and also I got key from ipstack. Okay,

I am going to get current user details by third-party API  as given below.

I have create this function under same class “GeoInfoProvider

       public async Task<string> GetGeoInfo()
        {
         //I have already created this function under GeoInfoProvider class.
         var ipAddress = await GetIPAddress();
         // When geting ipaddress, call this function and pass ipaddress as given below
          var response = await _httpClient.GetAsync($"http://api.ipstack.com/"+ipAddress+"?access_key=<your key>");
         if (response.IsSuccessStatusCode)
          {
            var json = await response.Content.ReadAsStringAsync();
            return json;
          }
          return null;
        }

When you will call this function “GetGeoInfo”, results in the following JSON response:

{
   "ip":"45.58.142.16",
   "type":"ipv4",
   "continent_code":"NA",
   "continent_name":"North America",
   "country_code":"US",
   "country_name":"United States",
   "region_code":"NV",
   "region_name":"Nevada",
   "city":"Paradise",
   "zip":"89120",
   "latitude":36.07670974731445,
   "longitude":-115.08950805664062,
   "location":{
      "geoname_id":5509952,
      "capital":"Washington D.C.",
      "languages":[
         {
            "code":"en",
            "name":"English",
            "native":"English"
         }
      ],
      "country_flag":"http:\/\/assets.ipstack.com\/flags\/us.svg",
      "country_flag_emoji":"\ud83c\uddfa\ud83c\uddf8",
      "country_flag_emoji_unicode":"U+1F1FA U+1F1F8",
      "calling_code":"1",
      "is_eu":false
   }
}

If you want to bind this JSON response data in your view model, you will create first a class for mapping JSON.NET attributes to the property names:

        public class GeoInfoViewModel
         {
            [JsonProperty("country_code")]
            public string CountryCode { get; set; }
            [JsonProperty("country_name")]
            public string CountryName { get; set; }
            [JsonProperty("region_code")]
            public string RegionCode { get; set; }
            [JsonProperty("region_name")]
            public string RegionName { get; set; }
            [JsonProperty("city")]
            public string City { get; set; }
            [JsonProperty("zip_code")]
            public string ZipCode { get; set; }
            [JsonProperty("latitude")]
            public decimal Latitude { get; set; }
            [JsonProperty("longitude")]
            public string Longitude { get; set; }
        }

Convert json format data in GeoInfoViewModel as given below.

      if (response.IsSuccessStatusCode)
        {
            var json = await response.Content.ReadAsStringAsync();
            Var model = new GeoInfoViewModel();
            model =JsonConvert.DeserializeObject< GeoInfoViewModel >( json);
        }

This post looked at accessing the ipstack geolocation API from .NET Core. The service allows you to retrieve location information such as country name, country code, zip code, city, longitude, latitude about a user based on IP address.

I am not affiliated with the site in any way but have used the service successfully on a couple of projects and can attest to its speed and reliability.

Mahira  khanna

Mahira khanna

I have the skills you need for you company blog, website, or other content materials

If findandsolve.com felt valuable to you, feel free to share it.

Comments



Report Response