How to retrieve client IP address in ASP.NET Core 3.1 API

I’m working on a project with ASP.NET Core 3.1 Web API and I need to capture the client’s IP address for logging purposes. I’ve tried several approaches but I’m not getting the correct results. Sometimes I get localhost or internal server addresses instead of the actual client IP.

I’m particularly confused about how to handle situations where the application is behind a proxy or load balancer. Can someone show me the proper way to extract the real client IP address from the HTTP request?

Here’s a basic example of what I’m trying to achieve:

[ApiController]
[Route("api/[controller]")]
public class ClientController : ControllerBase
{
    [HttpGet("info")]
    public IActionResult GetClientInfo()
    {
        // Need to get client IP here
        var clientIP = "???"; // How to get this?
        return Ok(new { ClientAddress = clientIP });
    }
}

Any help would be appreciated!

To retrieve the client’s actual IP address in ASP.NET Core 3.1, you should utilize HttpContext.Connection.RemoteIpAddress, with due caution regarding proxy configurations. In situations where your application may be using a proxy or load balancer, it’s essential to first check the X-Forwarded-For header, as this typically contains the true client IP. Here’s an example of how to implement it:

public string GetClientIP()
{
    var ipAddress = HttpContext.Connection.RemoteIpAddress;
    
    // Inspect forwarded IPs
    if (Request.Headers.ContainsKey("X-Forwarded-For"))
    {
        var forwardedIps = Request.Headers["X-Forwarded-For"].ToString();
        if (!string.IsNullOrEmpty(forwardedIps))
        {
            return forwardedIps.Split(',')[0].Trim();
        }
    }
    
    return ipAddress?.ToString() ?? "Unknown";
}

Ensure that the forwarded headers middleware is configured in your Startup.cs before UseRouting:

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

This will help avoid getting localhost addresses when your application is hosted behind proxies.

also check Request.HttpContext.Connection.RemoteIpAddress?.ToString(). if behind nginx or cloudflare, you should look at X-Real-IP header. cloudflare usually uses CF-Connecting-IP, so you might wanna check that based on your proxy config.

Had this exact problem last year with Azure behind Application Gateway. Most solutions miss the key part - you’ve got to configure forwarded headers correctly for your network setup. Define known networks and proxies or you’ll have security issues. In Program.cs or Startup.cs: csharp services.Configure<ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.KnownNetworks.Clear(); options.KnownProxies.Clear(); }); For your controller, make a helper method that checks multiple headers in order: csharp private string GetRealClientIP() { return Request.Headers["CF-Connecting-IP"].FirstOrDefault() ?? Request.Headers["X-Forwarded-For"].FirstOrDefault()?.Split(',')[0] ?? Request.Headers["X-Real-IP"].FirstOrDefault() ?? HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown"; } This works reliably across different setups - I’ve used it with AWS ALB and Cloudflare without issues.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.