Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 663
Chas Avatar asked May 03 '19 01:05

Chas


People also ask

How do I get client IP behind load balancer?

request. getHeader("X-FORWARDED-FOR") is always null even if property for sending x-forwarded-for is enabled on load balancer, and request. getRemoteAddr() is always giving the IP address of load balancer. When we disable ssl, this work fine, I got client IP, not the IP of the load balancer.

How do I get client IP address in asp net core?

Client IP address can be retrieved via HttpContext. Connection object. This properties exist in both Razor page model and ASP.NET MVC controller. Property RemoteIpAddress is the client IP address.


1 Answers

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.

like image 146
qkhanhpro Avatar answered Sep 28 '22 05:09

qkhanhpro