How to Detect Client IP Address Behind Cloudflare and Azure using ASP.NET MVC

Every HTTP request in ASP.NET MVC has UserHostAddress property, which stands for Gets the IP host address of the remote client. So it is as easy to get user's IP address as to write request.UserHostAddress?

No.
Never do it. You'll regret it. Most web app nowadays reside behind combination of DDOS protection, load balancer and reverse proxy. A typical example would be combination of Cloudlfare and Azure. These services create a chain of IP addresses which starts from client's address and ends with your web app. As a result request.UserHostAddress would contain IP address of you load balancer or DDOS protection, but rarely IP address of your client.

How to detect user's IP address then?
There is a HTTP Header called X-Forwarded-For designed for this purpose.

The X-Forwarded-For (XFF) HTTP header field is a common method for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or load balancer.

X-Forwarded-For is a list of IP address, where the first one is most likely user's IP address. We have to grab it, if it is present in the list, if not default to UserHostAddress. As a bonus, Cloudflare defines its own header for client IP address called CF-Connecting-IP. If you use Cloudflare look for it. If use some other cloud providers check for specific headers they might define. Example below should give you good general idea how to get user's IP address.

Keep in mind that these headers might not be present or might be spoofed, so never expect them to be present or rely on them for something important. At best they are good for guessing user's country, city and language.

References: