Develop a Geo-Location Service API with .NET Core and C# (Free Source Code)

Develop a Geo-Location Service API with ASP.NET

Table of Contents

Spread the love

Let's Develop a Geo-Location Service API with .NET. Because most Geo-Location API Services are Paid. This Project is easy for intermediate developers, but beginners can also do it if they have a basic understanding of Object-Oriented Programming and Basic Programming Concepts.

To understand the Project we will be working on, we should first understand these, below.????

What is a geolocation service?

The process of determining the position of a computer, phone, or other network-based device is known as geolocation. This estimated location is based on latitude and longitude measurements to narrow down the position to a city, zip code, street, and even address.

How to Create Geolocation API for free?

While most Geolocation API's out there are paid. I found a way to make things work for free using, Max Mind and .NET Core with some C#. I discuss the whole Project with Source Code, here in this Blog Post.

Is geolocation the same as GPS?

Geolocation works by propagating the device's longitudinal and latitudinal coordinates through a pre-built GPS in the device. On a map, the coordinates are used to create a complete address, which often includes a country, city, town/colony, building name, and street address.

Now that we have the Basics covered.

Let's see what we'll be covering Step-by-Step.

1. How to Develop a Geo-Location Service API with .NET and C#

2. How to Develop a Geo-Location Service API with .NET with C# (Source Code)

Let's get started.

Develop a Geo-Location Service API with .NET

I also made a video, in which I explain the Concept, build the API and test the results. Be sure to check it out, for a better understanding of the Project.

Develop a Geo-Location Service API with .NET

So, basically, our Goal with this Project is that we are going to build an API to get the country, and the location of any user visiting your website. 

We'll achieve this by building a .NET core C# Geolocation API.

For beginners in simple words.

What is an API?

An API or Application Programming Interface is simply that thing that allows developers to access a certain service from their code. For example, Facebook has a mobile application. You can post on Facebook through the application or through their website. But if you are a developer and you want to access Facebook (post on Facebook ) from your code. You want something that allows you to interact with Facebook. This “something” is the Facebook API.

So, according to the definition above, we have Facebook API, Twitter API, Google API, etc.

Like these others, we can build our own API to allow developers to access something from our database or from our services.

Essentially, In this Project, we are building an API that allows developers to get the geolocation of their users from our service.

You can use it on your own website if you are building a web application. And you want to know the country of each user visiting your website from their IP address. This will help you do the job. 

Or you can simply sell and provide this API on websites like Rapid API and other marketplaces.

On top, you can simply build the API to learn about .net core programming.

It's up to you!

Let's start.

Now before Moving on, if you Don't have Visual Studio Set up with C#. Check this Free Guide out, and come back after completing those steps.

If you have everything set up. Let's continue. 

Simply Open up visual studio and create a new project. 

Develop a Geo-Location Service API with .NET

Here select .net core web API and click on next.

Develop a Geo-Location Service API with .NET (Set up Project)

And then select the location. I will call it geolocation API and then click on next.

Select .NET for now and make sure check enable open API support and click on create.

You will see now how easy it is to build an API with .NET core.

So, we have the application here.

Now we have to setup some important settings.

Open controllers and delete this default controller.

Also, delete this default class, we don't need it.

And now I will go and create a new controller to use for our geolocation API.

Click on add new item. 

Search for the controller, and select API controller empty.

 I will name it here geo and click on add.

So, now we have a controller.

Confused? Don't Worry!

Even if you don't know it's a controller and how things work.

Wait and keep following along, you understand it in a little bit when you apply and run the API practically.

Here we have something called a route and we have this controller.

In the controller, we are going to create a function.

On top of the function, you can see “HttpGet.”

That is the route setup, and so we can access this endpoint by calling API/this action. (Which is get country)

Believe me. This all will make sense in a couple of minutes. Just hang in there.

So, now we have the function.

Our next step is that we want to implement the code that can get a country from an IP address.

I did a lot of research.

And I found out a lot of services. Most of them are paid and if not you can't use them, except for commercial use.

During my research, I found Max Mind which provides a Free geolocation database.

Develop a Geo-Location Service API with .NET

So, what you can do is:

Simply sign up on this website and download the database.

You can log into max mind and simply go here to download files and then go down and download Geo Lite2 Country.

Develop a Geo-Location Service API with .NET

Extract the downloaded file and you will find this .mmdb file containing the countries and the IP addresses.

So we can utilize it in our application.

The second step is to go back to our solution here and go to dependencies.

And then right-click, and select manage and Nuget packages.

Now you would want to install the max mind client library to interact with this database file.

So search here for max mind and install MaxMind.

Now, we are ready to read data from this file but before.

Go back here and copy file GeoLite2-Country.mmdb.

Add the file in your solution demo project.

You can also put it somewhere on your pc.

Hit paste let's rename it and make it geo for easy access.

And now let's read data from this file.

If you go back to max mind.

Use this documentation to install the Nuget package if you are using c sharp. If you are using java, node, php or any Programming Language.

You can copy the code from here.

Simply copy and paste it in the editor.

Replace the “path/to/maxmind” with the path where you placed your database file.

So copy-paste it here and make sure to add the “@” symbol because we are passing a path to escape characters and then add here geo.mmdb in the end (which is the file name.)

Now let's add a parameter string “ip address”

And replace it with the IP here.

Also in our case we want to get the country. So replace city with the country.

Now we have the response. I will return status code 200.

This means the request was successful.

And then return response.country.name  

Develop a Geo-Location Service API with .NET (Output)

Let's test this.

Open the API and run it.

Now before enjoying the output results. Understand the route concept.

To understand the route you can see here API/Geo/Get country 

This is the route here API/controller name

Which is Geo controller/the action (which is get country) which is the function name 

Then Finally /IP address (which is the parameter)

So, let's test the IP address.

Paste this example IP and hit execute.

And here we got the Output, “United States” 

Develop a Geo-Location Service API with .NET

So you give it an IP, and it will get the country for you.

Now let's make things more professional.

Create a model a class to return all data like country ISO code, and the country name.

Create a new folder called models.

And let's create a new class called Geo Class. 

And here let's add properties.

Now we can go back to our previous class. Let's add the new class objects here.

And retrieve the information we want from that object.

Below I am getting Country Name, Country Code, and Getting True/False Value about whether a country comes within the European Union.

And here we are.

Let's test it again

Enter an IP address, and Hit execute. 

Develop a Geo-Location Service API with .NET

And you've successfully Developed a Geo-Location Service API with .NET.

Develop a Geo-Location Service API with .NET with C# (Source Code)

There is definitely more to it than the code snippet is shown below. You can check out the Full Code on Github.

//start

using GeoLocationAPI.Models;
using MaxMind.GeoIP2;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace GeoLocationAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class GeoController : ControllerBase
    {

        [HttpGet("[action]/{ipAddress}")]
        public IActionResult GetCountry(string ipAddress)
        {
            //Change Path Here!!!!
            using (var reader = new DatabaseReader(@"E:\LearnWithHasan\Projects\C#\Geo Location API\Demo Project\db\geo.mmdb"))
            {
                var response = reader.Country(ipAddress);

                var geoLocation = new GeoClass();
                geoLocation.countryName = response.Country.Name;
                geoLocation.countryIsoCode = response.Country.IsoCode;
                geoLocation.IsInEuropeanUnion = response.Country.IsInEuropeanUnion;

                return StatusCode(StatusCodes.Status200OK, geoLocation);

            }


        }



    }
}

//end

Conclusion on Developing a Geo-Location Service API with .NET

I hope now you know how to build this api and get countries of users.

I believe you'll be interested in learning how to scrape google search results with c sharp and build a lot of special applications by scraping serp results.

If you do, you can check this Blog Post here.

Don't forget to get a source code and if you have any questions I'll be waiting for you in the comments section below.

Happy Coding!


Spread the love