Member-only story

How to Get the Client’s IP Address in C# (.Net Core) When Behind an NGINX Reverse Proxy

TenXers
2 min readJan 6, 2023

As a .NET developer, you may find yourself in a situation where you must get the client’s IP address for a web application. This is especially common when building web APIs that need to log or track requests.

However, things can get tricky when your application is behind an NGINX reverse proxy. In this case, the client’s IP address may not be immediately apparent, as the request appears to be coming from the NGINX server itself. How can you get the real client IP address when your .NET Core application is behind an NGINX reverse proxy?

First, it’s essential to understand that when a request is made to an NGINX server, it adds a few headers containing information about the client and the proxy. These headers are:

  • X-Real-IP: This header contains the client’s IP address.
  • X-Forwarded-For: This header contains a comma-separated list of IP addresses representing the client, and any intermediaries forwarded the request. The first IP in the list is the client’s IP address.

To get the client’s IP address in .NET Core, you can use the HttpContext object and read these headers from the request. Here’s an example of how to do this:

public string GetClientIpAddress(HttpContext context)
{
// Try to get the client IP address from the X-Real-IP header
var clientIp = context.Request.Headers["X-Real-IP"].Value;

// If the X-Real-IP header is not present, fall back to the RemoteIpAddress property
if (string.IsNullOrEmpty(clientIp))
{
clientIp = context.Connection.RemoteIpAddress.ToString();
}

return clientIp;
}

This code first checks for the X-Real-IP header and uses it if it exists. If the X-Real-IP header is not present, it falls back to the RemoteIpAddress property of the Connection object. This property returns the IP address of the client as seen by the web server, which in this case, is the NGINX server.

It’s important to note that this solution assumes that the NGINX server is correctly setting the X-Real-IP header. If this header is not present, the RemoteIpAddress property will be used, which may not always be the client's real IP address. To ensure that the NGINX server is correctly setting the X-Real-IP header, you will need to include the real_ip_header X-Real-IP; directive in your NGINX configuration file.

Note: If you are using Swagger to test your API, it’s essential to remember that the client IP address will always be the server’s IP address, as Swagger runs on the server side. If you rely on the X-Real-IP or RemoteIpAddress properties to get the client’s IP address, you may not get the expected results when testing with Swagger.

TenXers
TenXers

Written by TenXers

In this space, we share ideas, knowledge, and experiences that have allowed us to develop better IT skills to improve our work. Visit us: www.tenxers.io

No responses yet

Write a response