K8S群集中的RemoteIpAddress始终是入口IP

时间:2019-02-12 14:25:34

标签: nginx kubernetes nginx-ingress

我在本地裸机Kubernetes群集中运行ASP.NET Core webapi。没有外部负载均衡器,我正在使用NGINX入口。

我想获取用户的IP地址,并在.NET代码中使用environment

不幸的是,这正在获取nginx入口的IP地址(可能是给定名称空间的控制器)...

HttpContext.Connection.RemoteIpAddress

进行反向DNS查找可以解决...

::ffff:10.244.1.85

经过一段时间的Google搜索,我尝试将10-244-1-85.ingress-nginx.ingress-nginx.svc.cluster.local添加到我的服务定义中,但这没什么区别。

这似乎是一件微不足道的事情,是一个非常普遍的要求。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

首先尝试从头文件X-Forwarded-For获取ip,如下所示,如果它为null,则可以使用Connection.RemoteIpAddress。还要确保您的nginx configmap已按照截图启用了代理:
enter image description here

var ip = IPAddress.Parse(_accessor.ActionContext.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault());
            if (string.IsNullOrEmpty(ip.ToString()))
            {
                ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4();
            }
相关问题