"Knowledge has to be improved, challenged, and increased constantly, or it vanishes."

Geolocation in ASP.Net Core using Azure Maps

With the advancement in technologies, the world has become a global village. The people all over the world are interconnected. It is quite common that the companies publish their contents in multiple languages. With trade laws differ from country to country the developers need to make their website address the users who visit their web application by identifying the user’s country.

There are many ways a developer could get the country from the IP address. The option ranges from purchasing IP to country mapping database or use an API from a trusted provider that matches the customer IP with a country.

In this blog, let me show how you can achieve this with Azure Maps, that can help the developers map the IP to the corresponding country. Azure Maps provide geographic context to web and mobile applications though a set of geospatial services. You can view the set of services available in Azure maps from the below URL.

https://docs.microsoft.com/en-us/azure/azure-maps/about-azure-maps

One of the service offered by Azure Maps is the Geolocation service. This service returns the ISO country code for the given IP address. Developers can use this information and modify their application so that it displays appropriate content that is relevant to the user’s country.

https://docs.microsoft.com/en-us/rest/api/maps/geolocation/get-ip-to-location-preview

Now let us try this out in ASP.Net core application. For this purpose I created an ASP.Net core application. In the index page of the application, I am going to fetch the user’s IP address, pass it to the Azure Map API and get the ISO code for the corresponding country.

First thing, in my Azure account I added a resource of type Azure Maps in a resource group.

clip_image002

Azure Maps come with some free usage, for e.g. we can have 5000 requests free per month. View the pricing information in the below URL.

https://azure.microsoft.com/en-us/pricing/details/azure-maps/

Once you added the map to your Azure account, you can get authenticated to the map by Azure Active Directory of by Shared Key Authentication. In our case, we need to be authenticated with my web application, so I will be using the shared key authentication. You can get the keys to authenticate from the Azure maps.

image

As you can see, there are two keys, both will work. Azure provide two keys so that you can rotate them without interruption.

Now we are done with the Azure Maps configuration. Let us try this out in ASP.Net application. I created a ASP.Net Core application. In the index page, I am going to capture the IP address of the user and pass it to the Azure Maps Geolocation api and get the ISO code for the country. Then based on the iso Code, I will be displaying the country name. Cool!

In order to deserialize the Map response, I created the following classes

public class GeoData
{
    public string ipAddress { get; set; }
    public Country countryRegion { get; set; }
}

public class Country
{
    public string isoCode { get; set; }
}

Now in the Page OnGet() method, I have the following code.

var subscriptionKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
IP = Request.HttpContext.Connection.RemoteIpAddress.ToString();
using (HttpClient client = new HttpClient())
{
    var geolocationAPIUrl = $"https://atlas.microsoft.com/geolocation/ip/json?subscription-key={subscriptionKey}&api-version=1.0&ip={IP}";
    HttpResponseMessage response = await client.GetAsync(geolocationAPIUrl);
    var geo = await response.Content.ReadFromJsonAsync();
    RegionInfo myRegion = new RegionInfo(geo.countryRegion.isoCode);
    Country = myRegion.EnglishName;
    CountryNative = myRegion.DisplayName;
}

Let me explain the code a bit. You may notice I just used a local variable to store the subscription key, in production environment, you need to ensure you choose the secured mechanism to store the subscription key. Refer the following article for storing the secrets in your ASP.Net application.

https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-5.0&tabs=windows

In the Page Model, I created three string variables, one to store IP and the other two to store Country name in its native language and in English.

public String IP { get; set; }
public String Country { get; set; }
public String CountryNative { get; set; }

To get the IP address, I am using the RemoteIpAddress property

IP = Request.HttpContext.Connection.RemoteIpAddress.ToString();

Now use the HTTPClient GetAsync method to get the data from Azure Maps geolocation API. The following code will give me the two letter ISO code from the response.

geo.countryRegion.isoCode

ASP.Net has a RegionInfo class in the System.Globaliztion namespace that gives the access to the country name. You can create the RegionInfo object by passing the ISOCode of the country.

https://docs.microsoft.com/en-us/dotnet/api/system.globalization.regioninfo?view=net-5.0

The RegionInfo class’s property “EnglishName” will give the name of the country in English and the “DisplayName” property will give the name of the country in the native language. I set the values to variables to use it in the .cshtml file

RegionInfo myRegion = new RegionInfo(geo.countryRegion.isoCode);
Country = myRegion.EnglishName;
CountryNative = myRegion.DisplayName;

Now, let me display the IP address and the country details in my CSHTML page.


<div class="text-center">
    <h1>Welcome</h1>
    <div>Your IP address is @Model.IP and your country is @Model.CountryNative (@Model.Country)</div> 
</div>

Now let us run the application and see the result.

image

Thank you for reading!

1 Comment

  • Welcome to our comprehensive guide on mastering the Salesforce Certified OmniStudio Consultant Exam. As experts in Salesforce consulting and training, we understand the importance of achieving certification to advance your career and expertise in the field of Salesforce implementation and customization.

Add a Comment

As it will appear on the website

Not displayed

Your website