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…

--

--

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