How to get user location from a web service in c#

Introduction


Have you ever wondered on how to get user location based on the network the user is currently on? Maybe you want to display the user country based on location or you want to disable some countries that shouldn't access your app, Your in the right place!!!

freegeoip.net provides a public HTTP API for software developers to search the geolocation of IP addresses. It uses a database of IP addresses that are associated to cities along with other relevant information like time zone, latitude and longitude.

Let's see some codes in C#.

C# Impelmentation


1. Create a Location class that will be used as a data transfer object. It will contain properties to hold the data return from the web service.




















2. Call the ReadAsync<T> method of  the HttpClient Class. The method will handle serialization of object to the response object.

























Let's play with it a little

   
if(currentLocation == "Nigeria"){
      //allow
}else{
    //deny
}


Run it in the console and you would be surprised by what you see.

NodeJS Implementation

Coming soon...

Conclusion


I hope you have all enjoyed your way through this tutorial, it's been fun coding this. This kind of code can also be used for security reasons and i personally use it in my projects and it has been working for me. If you have a better implementation, lets see it.  


Comments

  1. Please ignore the class name i use. Use a suitable one.

    ReplyDelete

Post a Comment

Popular posts from this blog

Paystack In Asp.Net MVC

Solved: Jwt Authentication in Asp.Net Web Api And Mvc

Coingate in .Net