RU EN
Dec 23, 2023

How to get client IP address and location information in ASP.NET Core

How to get client IP address and location information in ASP.NET Core
Автор:
Источник:
Просмотров:
7985
How to get client IP address and location information in ASP.NET Core favorites 1

This article will teach us how to retrieve the client’s IP address and location information in ASP.NET Core web development.

Retrieve the client IP from HttpContext

In ASP.NET Core, you can easily get the client IP address from the HttpContext object in the Controller, making it simple to access this important information during a web request:

public class MyIpController : ControllerBase {     [HttpGet]     public ActionResult Get()     {         var ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();         // ...     } }

This approach works well when our application is directly exposed to the internet, operating without the intermediary layer of a reverse proxy.

Retrieve real client IP behind reverse proxy

However, it’s common for most web applications to use intermediary layers such as reverse proxies or load balancers in their architecture.

The direct retrieval method might yield the proxy IP instead of the client’s.

To obtain the actual client’s IP address, we can extract it from the ‘X-Forwarded-For’ header value.

To do this, we have to configure the ForwardHeaderOptions in the Program.cs first:

// forward headers configuration for reverse proxy builder.Services.Configure<ForwardedHeadersOptions>(options => {     options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;     options.KnownNetworks.Clear();     options.KnownProxies.Clear(); });

Then, in the Controller, we can retrieve the actual client IP address:

public class MyIpController : ControllerBase {     [HttpGet]     public ActionResult Get()     {         var ipAddress = HttpContext.GetServerVariable("HTTP_X_FORWARDED_FOR");         // ...     } }

Retrieve real client IP behind Cloudflare

If we use Cloudflare, we can access the real client IP from the ‘CF-CONNECTING-IP’ header:

public class MyIpController : ControllerBase {     [HttpGet]     public ActionResult Get()     {         var ipAddress = Request.Headers["CF-CONNECTING-IP"];         // ...     } }

Get the client’s IP location information

To obtain location information based on the client’s IP address, we will utilize the services provided by ip-api.com.

First, we create the IpApiClient class:

public class IpApiClient(HttpClient httpClient) {     private const string BASE_URL = "http://ip-api.com";     private readonly HttpClient _httpClient = httpClient;     public async Task<IpApiResponse?> Get(string? ipAddress, CancellationToken ct)     {         var route = $"{BASE_URL}/json/{ipAddress}";         var response = await _httpClient.GetFromJsonAsync<IpApiResponse>(route, ct);         return response;     } }

The IpApiResponse class:

public sealed class IpApiResponse {     public string? status { get; set; }     public string? continent { get; set; }     public string? country { get; set; }     public string? regionName { get; set; }     public string? city { get; set; }     public string? district { get; set; }     public string? zip { get; set; }     public double? lat { get; set; }     public double? lon { get; set; }     public string? isp { get; set; }     public string? query { get; set; } }

We need to add and register the HttpClient for IpApiClient within the service container, which can be done in the Program.cs file:

builder.Services.AddHttpClient<IpApiClient>();

Now we can retrieve the client’s IP location information:

[HttpGet] public async Task<ActionResult> Get(CancellationToken ct) {     try     {         var ipAddress = HttpContext.GetServerVariable("HTTP_X_FORWARDED_FOR") ?? HttpContext.Connection.RemoteIpAddress?.ToString();         var ipAddressWithoutPort = ipAddress?.Split(':')[0];         var ipApiResponse = await _ipApiClient.Get(ipAddressWithoutPort, ct);         var response = new         {             IpAddress = ipAddressWithoutPort,             Country = ipApiResponse?.country,             Region = ipApiResponse?.regionName,             City = ipApiResponse?.city,             District = ipApiResponse?.district,             PostCode = ipApiResponse?.zip,             Longitude = ipApiResponse?.lon.GetValueOrDefault(),             Latitude = ipApiResponse?.lat.GetValueOrDefault(),         };         return Ok(response);     }     catch (Exception ex)     {         return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);     } }

Sometimes, the client IP includes a port number.
We can remove the port number using the following code:

var ipAddressWithoutPort = ipAddress?.Split(':')[0];

• • •

I created a simple application to showcase the concepts discussed in this article:

MYIPJUL

The source code for that application can be found here:

GitHub - juldhais/MYIP: Example of how to retrieve client’s IP and location in ASP.NET Core

Thank you for reading. 👍

Файлы

Похожее
Jun 27, 2024
Author: Dayanand Thombare
Introduction Caching is a technique used to store frequently accessed data in a fast-access storage layer to improve application performance and reduce the load on backend systems. By serving data from the cache, we can avoid expensive database queries or...
Jan 29, 2024
Author: Alex Maher
Performance tricks & best practices, beginner friendly Hey there! Today, I’m sharing some straightforward ways to speed up your .NET Core apps. No fancy words, just simple stuff that works. Let’s dive in! • • • 1. Asynchronous programming Asynchronous...
Jun 7, 2024
Author: Dev Leader
In software engineering, composition plays an important role in object-oriented programming. If you’ve come across other articles or videos I’ve put out about object-oriented programming, you’ll know that I try to push composition over inheritance as much as I can....
Jun 8, 2023
Author: Juan Alberto España Garcia
At the end of this article you will understand what “^(?=.*[a-z])(?=.*[A-Z])(?=.*).*” means Introduction to C# Regex: why it’s a powerful tool for text manipulation Before diving into the magical world of regular expressions, let’s get an idea of why using...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Почему сеньоры ненавидят собеседования с кодингом, и что компании должны использовать вместо них
5 приемов увеличения продуктивности разработчика
Как мы столкнулись с версионированием и осознали, что вариант «просто проставить цифры» не работает
Не одними Unity и Unreal Engine. Альтернативные игровые движки
WAF и RASP: в чём разница и что лучше для безопасности веб-приложений
Почему программисты не стареют: эффект кодера после 40
Почему As Code — это не просто тренд, а новая реальность разработки
Как сделать полезный дашборд: советы и идеи
Мои 7 правил при собеседовании разработчиков
Модуль, пакет, библиотека, фреймворк: разбираемся в разнице
Boosty
Donate to support the project
GitHub account
GitHub profile
Complete your gift to make an impact