http {
# 转发的访问地址
upstream backend {
server 127.0.0.1:7015 weight=2 max_fails=5 fail_timeout=10s;
server 127.0.0.1:7016 weight=2 max_fails=5 fail_timeout=10s;
server 127.0.0.1:7017 weight=2 max_fails=5 fail_timeout=10s;
}
}
server {
# 监听8036 (IIS中不要再设定8036,否则端口冲突)
listen 8036;
# 将8036端口的请求代理到backend
location / {
# 设置真实IP头信息
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 反向代理到后端服务器
proxy_pass http://backend;
}
}
在webAPI中如果仍然用 var realIp = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();获取到的IP只会是127.0.0.1
要根据nginx中的配置去获取
[HttpPost]
public async Task<IActionResult> BatchSubmitGrindIng(List<QMS_GrindingTestRecord> modules)
{
var realIp = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
//// 如果Nginx使用X-Forwarded-For
if (_httpContextAccessor.HttpContext.Request.Headers.ContainsKey("X-Forwarded-For"))
{
realIp = _httpContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"];
}
modules.ForEach(x =>
{
x.TestMacNum = realIp;
});
var res = await _grindingService.BatchSubmitGrindIng(modules);
return Ok(res);
}