How can an ASP.NET Core MVC app get client IP address when server is behind AWS ELB?
Asked Answered
D

2

9

I'm running an ASP.NET Core MVC app on AWS in an Elastic Beanstalk environment that includes ELB.

I use this code to get the IP address of the client:

HttpContext.Connection.RemoteIpAddress.ToString()

However, this returns the IP address of the load balancer, not the IP address of the client. I believe RemoteIPAddress returns the address stored in the X-Forwarded-For HTTP header, which in theory should be the client IP, but it isn't.

So I followed the instructions to enable Proxy Protocol for ELB based on these instructions.

But still no luck. The RemoteIPAddress still returns the same ELB IP instead of the client IP.

Has anyone been able to get client IP when running an ASP.NET Core MVC app on AWS behind ELB? If so, how?

Any help would be greatly appreciated.

Dispread answered 3/5, 2019 at 1:16 Comment(0)
M
7

You can just look at the X-Forwarded-For header for the original IP address.

To access the Headers, look at HttpContext.Current.Request.Headers or HttpContext.Request.Headers.

I successfully listed the original client IP when running an ASP.NET Core MVC app on AWS behind ELB with that method.

Metameric answered 3/5, 2019 at 4:48 Comment(1)
This worked! To help anyone else who might have this same problem, here's the exact code I used that worked: HttpContext.Request.Headers["X-Forwarded-For"].ToString()Dispread
D
0

Here's how I solved it:

if(HttpContext?.Request?.Headers?.TryGetValue("X-Forwarded-For", out var values) == true)
{
    return $"X-Forwarded-For: {string. Join(values,',')}";
} 
return $"Connection.RemoteIpAddress: {HttpContext?.Connection?.RemoteIpAddress}";
Decemvir answered 28/6, 2024 at 17:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.