通过MVC 5控制器在Azure中获取客户端IP [英] Get client IP in Azure through MVC 5 controller
问题描述
我找不到与此有关的问题或针对Azure的帖子,并且我不确定Azure环境与我的测试环境中有什么不同会导致此问题. 我已经尝试了几种方法来使其正常工作,但是我做错了.请注意,这不是 Webapi,所以据我所知,使用HttpRequestMessage也不起作用.
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:
方法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();
方法2:
string userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(userIP))
{
userIP = Request.ServerVariables["REMOTE_ADDR"];
}
return userIP;
谢谢.
推荐答案
读取此标头中传输的值:
Read the value transported in this header:
x-forwarded-for: "91.23.44.24:52623"
请注意,在IP地址后面有一个源端口号,因此请相应地进行解析.
Note there's a source port number trailing the IP address, so parse accordingly.
此外,正如 @NicoD 正确指出的那样,有问题的标头
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"
语法
X-Forwarded-For: <client>, <proxy1>, <proxy2>
<client>
客户端IP地址
<proxy1>, <proxy2>
如果请求通过多个代理,则会列出每个连续代理的IP地址.这意味着,最右边的IP地址是最新代理的IP地址,最左边的IP地址是发起客户端的IP地址.
<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?
来自 https://tools.ietf.org/html/rfc7239 :>
5.2.转发给
[...]此参数可以改为包含IP 地址(以及可能的端口号).
5.2. Forwarded For
[...] this parameter MAY instead contain an IP address (and, potentially, a port number).
所有客户端请求都在前端层终止,并通过应用程序请求路由"代理到您的Web工作者(托管MVC5应用程序).
All client requests are terminated in the frontend layer and proxied via Application Request Routing to your web worker (hosting the MVC5 application).
这篇关于通过MVC 5控制器在Azure中获取客户端IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!