Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Products
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Integrating IP Geolocation API in ASP.NET Core to Detect User Location by IP Address

Integrating IP Geolocation API in ASP.NET Core to Detect User Location by IP Address

Date- May 16,2026 224
aspnetcore geolocation

Overview

IP Geolocation is a technology that enables the identification of a user's geographic location based on their IP address. This process involves querying a geolocation database that maps IP address ranges to geographical locations, providing information such as city, region, country, latitude, longitude, and even timezone. The ability to detect user location is essential for various applications, from delivering localized content to enhancing security protocols by identifying suspicious activities.

One of the primary problems that IP Geolocation solves is the challenge of delivering personalized experiences to users. For instance, an e-commerce website can show products relevant to a user's location, while a news platform can present news articles that are pertinent to the user's region. Additionally, IP Geolocation plays a significant role in regulatory compliance, such as GDPR, where it is crucial to understand the geographical origin of user data.

Prerequisites

  • ASP.NET Core SDK: Ensure that you have the latest version of the .NET SDK installed on your machine.
  • Geolocation API Key: Sign up for an IP Geolocation service (e.g., ipinfo.io, ipstack.com) to obtain an API key.
  • Basic ASP.NET Core Knowledge: Familiarity with creating controllers and services in ASP.NET Core.
  • HTTP Client Knowledge: Understanding of making HTTP requests in .NET.

Understanding IP Geolocation

IP Geolocation works by mapping IP addresses to physical locations. Various services maintain databases that correlate IP addresses with geographical data. When a user accesses a web application, their IP address can be captured, and an API call can be made to retrieve their location information. The accuracy of this information can vary based on the data source and the user's network configuration.

Geolocation data can be used for numerous purposes, including fraud detection, content customization, and traffic analysis. However, it is essential to understand the limitations and privacy implications associated with using such data, as users may have concerns over how their location data is utilized.

How IP Addresses Are Assigned

IP addresses are assigned through regional Internet registries (RIRs), which distribute blocks of addresses to Internet Service Providers (ISPs). When a user connects to the internet, their ISP assigns them an IP address from its pool. This address can be dynamic (changing over time) or static (fixed). Geolocation services utilize these ranges to determine the user's probable location.

Setting Up an ASP.NET Core Application

To start using an IP Geolocation API in ASP.NET Core, we first need to create a new ASP.NET Core application. This can be done using the .NET CLI or Visual Studio. Below is an example of creating a new Web API project using the CLI.

dotnet new webapi -n GeoLocationDemo

This command creates a new ASP.NET Core Web API project named GeoLocationDemo. Next, we need to install the necessary NuGet packages for making HTTP requests. The HttpClient class in .NET is ideal for this purpose.

dotnet add package Microsoft.Extensions.Http

After installing the package, we can set up our HTTP client in the Startup.cs file.

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

This setup registers an HTTP client service that can be injected into our controllers. The ConfigureServices method is where we add the necessary services, including the HTTP client and controllers.

Creating a Geolocation Service

Next, we will create a service that interacts with the Geolocation API to fetch user location data. This service will encapsulate the logic for making the API call and handling responses.

public class GeoLocationService
{
private readonly HttpClient _httpClient;
private readonly string _apiKey = "YOUR_API_KEY";
private readonly string _apiUrl = "https://ipinfo.io/{ip}/json";

public GeoLocationService(HttpClient httpClient)
{
_httpClient = httpClient;
}

public async Task GetLocationAsync(string ip)
{
var response = await _httpClient.GetStringAsync(_apiUrl.Replace("{ip}", ip) + "?token=" + _apiKey);
return JsonConvert.DeserializeObject(response);
}
}

This GeoLocationService class takes an HttpClient as a dependency and uses it to call the Geolocation API. The GetLocationAsync method constructs the request URL, makes the API call, and deserializes the response into a GeoLocationData object.

Make sure to replace YOUR_API_KEY with the actual API key obtained from the geolocation provider.

Defining the GeoLocationData Model

Next, we need to define the model that represents the response data from the API. This model should include properties that correspond to the data returned by the API.

public class GeoLocationData
{
public string Ip { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
public string Loc { get; set; }
public string Org { get; set; }
public string Postal { get; set; }
}

This GeoLocationData class includes properties for IP address, city, region, country, location coordinates (latitude and longitude), organization, and postal code. These properties will hold the data retrieved from the API.

Building a Controller to Use the Service

We will now build a controller that utilizes our GeoLocationService to return user location data based on their IP address. This controller will expose an API endpoint that clients can call to get geolocation information.

[ApiController]
[Route("api/[controller]")]
public class GeoLocationController : ControllerBase
{
private readonly GeoLocationService _geoLocationService;

public GeoLocationController(GeoLocationService geoLocationService)
{
_geoLocationService = geoLocationService;
}

[HttpGet("{ip}")]
public async Task GetLocation(string ip)
{
var location = await _geoLocationService.GetLocationAsync(ip);
return Ok(location);
}
}

This GeoLocationController class defines a single GET endpoint that takes an IP address as a parameter. It calls the GetLocationAsync method of the GeoLocationService and returns the location data in the response.

Testing the API Endpoint

To test the API endpoint, run the application and use a tool like Postman or a web browser to access http://localhost:5000/api/geolocation/{ip}, replacing {ip} with an actual IP address. The response should return a JSON object containing the geolocation data.

Edge Cases & Gotchas

When integrating with an IP Geolocation API, there are several edge cases and potential pitfalls to consider. One common issue is handling invalid or private IP addresses. For example, requests coming from the localhost (e.g., 127.0.0.1) will not return meaningful geolocation data.

[HttpGet("{ip}")]
public async Task GetLocation(string ip)
{
if (ip == "127.0.0.1" || ip == "::1")
{
return BadRequest("Invalid IP address");
}
var location = await _geoLocationService.GetLocationAsync(ip);
return Ok(location);

This code snippet adds a simple check to return a bad request response if the IP address is localhost. Another pitfall is rate limiting imposed by geolocation services, which can limit the number of requests made in a specific time frame. Ensure that your application implements proper error handling to manage HTTP status codes returned by the API gracefully.

Performance & Best Practices

To optimize the performance of your IP Geolocation implementation, consider caching the results of API calls. This can significantly reduce the number of requests made to the geolocation API and improve response times for repeat visitors. You can use in-memory caching or distributed caching depending on your application architecture.

services.AddMemoryCache();

public class GeoLocationService
{
private readonly IMemoryCache _cache;
public GeoLocationService(HttpClient httpClient, IMemoryCache cache)
{
_httpClient = httpClient;
_cache = cache;
}

public async Task GetLocationAsync(string ip)
{
if (!_cache.TryGetValue(ip, out GeoLocationData location))
{
var response = await _httpClient.GetStringAsync(_apiUrl.Replace("{ip}", ip) + "?token=" + _apiKey);
location = JsonConvert.DeserializeObject(response);
_cache.Set(ip, location, TimeSpan.FromMinutes(10));
}
return location;
}
}

In this example, we inject IMemoryCache into the GeoLocationService and check the cache before making an API call. If the location data is not in the cache, we retrieve it from the API and store it in the cache for future use.

Real-World Scenario: Location-Based Content Display

In a practical scenario, we can utilize the geolocation data to customize content displayed to users based on their location. For example, consider a travel website that wants to show different travel packages based on where users are located.

[HttpGet("packages")]
public async Task GetPackages(string ip)
{
var location = await _geoLocationService.GetLocationAsync(ip);
var packages = GetPackagesByRegion(location.Region);
return Ok(packages);
}

This controller method retrieves the user's location and then calls a hypothetical GetPackagesByRegion method to fetch relevant travel packages. This approach personalizes the user experience and increases engagement.

Conclusion

  • IP Geolocation is a powerful tool for determining user locations based on their IP addresses.
  • Integrating an IP Geolocation API in ASP.NET Core allows developers to access location data for various applications and use cases.
  • Implement caching to improve performance and reduce the load on the geolocation service.
  • Be mindful of edge cases, such as private IP addresses and rate limits imposed by the geolocation API.
  • Real-world applications of IP Geolocation can significantly enhance user experience through personalized content delivery.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Implementing Grok API Integration in ASP.NET Core Applications: A Comprehensive Guide
Apr 04, 2026
Implementing API Key Authentication Middleware in ASP.NET Core Web API
Jun 10, 2026
Integrating Currency and Exchange Rate API in ASP.NET Core for Real-Time Forex Data
May 28, 2026
Barcode Scanning and Generation in ASP.NET Core with ZXing.NET
May 27, 2026
Previous in ASP.NET Core
Integrating HERE Maps API in ASP.NET Core: Comprehensive Guide on…
Next in ASP.NET Core
SignalR Integration in ASP.NET Core: Building a Real-Time WebSock…
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    CWE-269: Improper Privilege Management - Implementing the … 328 views
  • 2
    Building Custom Bedrock Add-Ons with JavaScript: A Complet… 1,928 views
  • 3
    Elasticsearch Integration in ASP.NET Core - Full-Text Sear… 240 views
  • 4
    Error-An error occurred while processing your request in .… 11,953 views
  • 5
    Fix Gemini API Error 429: Quota Exceeded on Free Tier (Sys… 815 views
  • 6
    Send Email With HTML Template And PDF Using ASP.Net C# 17,167 views
  • 7
    Integrating Google reCAPTCHA Validation in ASP.NET MVC 6,456 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26677 views
  • Exception Handling Asp.Net Core 21714 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 21166 views
  • How to implement Paypal in Asp.Net Core 20126 views
  • Task Scheduler in Asp.Net core 18195 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1780
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Products
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor