How to Get Visitors Country from Their IP in ASP.NET

In this tutorial, we are going to learn how to consume a web-service within an ASP.NET Core web application to get information about visitors from their IP addresses. For that, we will do the following steps:

  • Create an ASP.NET Core web application
  • Implement a controller that consumes the ipstack.com web-service
  • Upload the application to Microsoft Azure to be able to test it

First, we will create a basic ASP.NET Core web application. Open the Visual Studio IDE (I used version 16.5.4) and click on the button “Create a new project“.

In the “Create a new project” window, select the “ASP.NET Core Web Application” and click on the “Next” button.

Next, provide the project name, solution name, and location path. Click on the “Create” button.

In the next windows, select the “Web Application (Model-View-Controller)” template. Ensure that the version of the ASP.NET Core Framework is set to 3.1 and that the option “Configure for HTTPs” is checked. We also don’t want any authentication and Docker Support. Click on the “Create” button to finalize the creation process.

Hit F5 to test the application. You should see the output as in the image below.

In the next step, we have to obtain a free API key that will allow us to consume the ipstack.com web-service. For that, go to the ipstack.com website (https://ipstack.com) and register for the free plan. Of course, you can use any other web-service of your choice.

Upon your registration, login, and go to the dashboard. There you will find your API key. Copy it.

Next, switch back to the project. In the “Solution Explorer“, expand the “Controllers” folder and double-click on the “HomeController.cs” file to open it.

In the “HomeController.cs” file, add a new string constant to the HomeController class. Name it “apiKey” and assign the API key from the ipstack.com dashboard to it.

private const string apiKey = "25xxx1a23bxxxxxacf9ac3xxxxxxxxxx";

To consume the web-service, we have to install the Newtonsoft.Json package first, which will help us to process the web-service responses. In the “Solution Explorer“, right-click on the project name and select “Manage NuGet Packages…” from the context menu. Activate the “Browse“-Tab und type “Newtonsoft.Json” in the search field. Next, select the package “Newtonsoft.Json” and click the “Install” button.

Now, let us create a Model that will represent a visitor. In the “Solution Explorer” right-click on the “Models” folder and select “Add -> Class…” from the context menu.

In the “Add new item” window, enter “Visitor” in the “Name” field. This will be the name of our class. Click on the “Add” button to create the class.

Open the “Visitor.cs” file and replace its content with the following code:

namespace ipstack_tutorial.Models
{
    public class Visitor
    {
        public int ID { get; set; }
        public string IP { get; set; }
        public string CountryName { get; set; }
        public string CountryCode { get; set; }
    }
}

As you can see, our model is pretty simple. It has only four properties: ID, IP, CountryName, and CountryCode. We are going to use instances of that model is to store information about visitors.

Now, we have everything set up to consume the web-service. Let us implement the logic. First. open the “HomeController.cs” file and add the following “using”-instructions at the top of the file.

using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;

Next, replace the delete the “Index” method and insert instead of it the following code:

public async Task<IActionResult> IndexAsync()
        {
            Visitor visitor = new Visitor();
            visitor.IP = Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

            string requestUri = $"http://api.ipstack.com/{visitor.IP}?access_key={apiKey}";

            using (HttpClient httpClient = new HttpClient())
            {

                try
                {
                    using (HttpResponseMessage httpResponse = await httpClient.GetAsync(requestUri))
                    {
                        if (httpResponse != null && httpResponse.IsSuccessStatusCode)
                        {
                            string apiResponse = await httpResponse.Content.ReadAsStringAsync();
                            JObject jObject = JObject.Parse(apiResponse);
                            visitor.CountryCode = jObject.SelectToken("country_code").ToString();
                            visitor.CountryName = jObject.SelectToken("country_name").ToString();
                        }
                    }
                }
                catch (HttpRequestException ex)
                {
                    visitor.CountryName = ex.ToString();
                }
            }

            return View(visitor);
        }

Let’s take a look at what we are doing in the “IndexAsync” method.

First, we create a new instance of the “Visitor” model to be able to store the information about the visitor.

Next, we used the “Request” instance to retrieve the IP-address of the visitor. We also saved the address in the “IP” property of our model.

Using the retrieved IP-address and the declared earlier API key, we created a request URI for the web-service.

In the next step, we instantiated a HttpClient and made a request to the web-service using URI. Upon the reception of a response, we ensured that the response is valid. Next, we parsed the response to a JSON object and retrieved the country information of the visitor, which we saved to our model.

Finally, we passed our model as a parameter to the “View” to be able to insert it into the HTML code.

Now, let us create a View that will use the model to render information about the visitor. For that, open the View-File “Index.cshtml“, which lies inside the folder “Views/Home“. This is the View for the method “IndexAsync“, that we have just implemented.

Replace the content of the file with the following code:

@{
    ViewData["Title"] = "Home Page";
}

@model Visitor

    <div class="text-center">
        <h1 class="display-4">ipstack tutorial</h1>
        <p>IP-address: @Model.IP</p>
        <p>Conuntry: @Model.CountryName</p>
        <p>Conuntry Code: @Model.CountryCode </p>
    </div>

As you can see, the code is very simple. First, we set the title of the webpage. Next, we defined the type of model that the Controller will pass to the View. Finally, we accessed the properties of the model and added their content to the HTML-code.

At this point, we are finished with the application. However, if you hit F5 and run the application, then it won’t work correctly. This is because we run it locally and therefore do not have a real IP-address. Thus, we have to upload the application to a real server.

For that, you can upload the application to your server or use a cloud service provider like Amazon, Google, or Microsoft. In this tutorial, I will use the Azure cloud service from Microsoft, since it is free.

Go to the Azure portal https://portal.azure.com/#home and log in. If you do not have an account, then you will have to sign up.

Once logged in, we need to create a resource. Click on the navigation pane symbol in the top left corner and select “Create a resource“.

On the next page, select “Web” and “Web App“. This will lead you to the configuration page of the app. You will need to select a subscription plan and a resource group. If you do not have a subscription plan, then you will need to create one (I recommend the “Pay-As-You-Go” option).

Next, you need to provide a unique name for the app, select “Code” as a publish method, “Windows” as an operating system, and a region of your choice.

Finally, be sure to select the Free Plan (F1) for the option “SKU and size”. Otherwise, it can cost you a lot of money!!!

Next, go to the “Monitoring” tab and turn off the “Application Insights” option.

Finally, click on the “Review + create” button, check your parameters, and click on the “Create” button.

The deployment process will take some time. Once it is completed, click on the “Go to resource” button.

Now, we can publish our application to the app service. Go back to the Visual Studio editor, right-click on the project name in the “Solution Explorer“, and select “Publish…“.

In the “Pick a publish target” window, select “App Service“, activate the “Select Existing” option, and click on the “Create Profile” button.

In the next window, search and select the app service you have just created, and click “OK“. After that, the Visual Studio editor will create a publishing profile. Once done, you can click on the “Publish” button to upload your application to the app service.

As soon as you published the application you can open a browser and navigate to the web address of the app service. In my case, it is: https://ipstack.azurewebsites.net/

If everything is OK, then you will be able to see an output like in the image below.

That is all!

%d