Get client IP in Azure through MVC 5 controller

为君一笑 提交于 2019-12-11 00:13:42

问题


I can't find a question or post specific to Azure for this, and I'm not sure what's different in the environment in Azure versus my testing environments that would cause this. I've tried a few methods to get this to work but I'm not coming right. Please note this isn't Webapi, so using the HttpRequestMessage, as far as I know, is not going to work either.

Here's what I've tried so far:

Method 1:

string ipAddress = "";
IPHostEntry Host = default(IPHostEntry);
Host = Dns.GetHostEntry(System.Environment.MachineName);
ipAddress = Host.AddressList.SingleOrDefault(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).MapToIPv4().ToString();

Method 2:

string userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(userIP))
{
    userIP = Request.ServerVariables["REMOTE_ADDR"];
}
return userIP;

Thanks in advance.


回答1:


Read the value transported in this header:

x-forwarded-for: "91.23.44.24:52623"

Note there's a source port number trailing the IP address, so parse accordingly.

Also, as @NicoD correctly points out, the header in question may contain an array of proxy servers the request traversed. For example:

x-forwarded-for: "91.23.44.24:52623, 91.23.44.155"

Syntax

X-Forwarded-For: <client>, <proxy1>, <proxy2>

<client> The client IP address

<proxy1>, <proxy2> If a request goes through multiple proxies, the IP addresses of each successive proxy is listed. This means, the right-most IP address is the IP address of the most recent proxy and the left-most IP address is the IP address of the originating client.

What about that glaring port number you ask?

From https://tools.ietf.org/html/rfc7239:

5.2. Forwarded For

[...] this parameter MAY instead contain an IP address (and, potentially, a port number).

All client requests are terminated in the frontend layer and proxied via Application Request Routing to your web worker (hosting the MVC5 application).



来源:https://stackoverflow.com/questions/48618450/get-client-ip-in-azure-through-mvc-5-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!