转自:https://www.cnblogs.com/mypath/articles/5239687.html
https://imququ.com/post/x-forwarded-for-header-in-http.html
一般来说,X-Forwarded-For是用于记录代理信息的,每经过一级代理(匿名代理除外),代理服务器都会把这次请求的来源IP追加在X-Forwarded-For中
来自4.4.4.4的一个请求,header包含这样一行
X-Forwarded-For: 1.1.1.1, 2.2.2.2, 3.3.3.3
代表 请求由1.1.1.1发出,经过三层代理,第一层是2.2.2.2,第二层是3.3.3.3,而本次请求的来源IP4.4.4.4是第三层代理
实际操作:
首先是在使用 nginx 中,需要加入 X-Forwarded-For 配置,当然要是自己换成别的头也可以,只不过这个比较标准:
server { listen 80; server_name some.test.com; location / { proxy_pass http://172.26.190.212:7003; proxy_set_header X_Real_IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_connect_timeout 600; proxy_send_timeout 600; proxy_read_timeout 600; send_timeout 600; } }
然后在 asp.net core 中,就可对其进行读取了,以下是测试代码:
public ActionResult<object> RemoteIpTest() { var request_host = Request.Host.Host + ":" + Request.Host.Port; var remoteIp = Request.HttpContext.Connection.RemoteIpAddress.ToString() + ":" + Request.HttpContext.Connection.RemotePort; var localIp = Request.HttpContext.Connection.LocalIpAddress.ToString() + ":" + Request.HttpContext.Connection.LocalPort; var x_forwarded_for = new StringValues(); var x_forwarded_remote_ip = ""; if (Request.Headers.ContainsKey("X-Forwarded-For")) { x_forwarded_for = Request.Headers["X-Forwarded-For"]; if (x_forwarded_for.Any()) { var ip_list = x_forwarded_for.Last().Split(',', StringSplitOptions.RemoveEmptyEntries); if (ip_list.Any()) { x_forwarded_remote_ip = ip_list.First().Trim(); } } } var x_real_ip = new StringValues(); if (Request.Headers.ContainsKey("X_Real_IP")) { x_real_ip = Request.Headers["X_Real_IP"]; } return new { request_host, remoteIp, localIp, x_forwarded_remote_ip, x_forwarded_for, x_real_ip }; }