在.net framwork时我们可以使用如下代码获取IP:

string ip = HttpContext.Request.UserHostAddress.ToString();

到了Netcore时代这个UserHostAddress属性已经从request中找不到了,可以使用以下方法代替:

var remoteIP = HttpContext.Connection.RemoteIpAddress.ToString();
var localIP = HttpContext.Connection.LocalIpAddress.ToString();

本文地址:https://lebang2020.cn/details/210127qjqh5ygn.html

几种取值方式

  • HTTP 层:HttpContext.Connection.RemoteIpAddress(.NET Core 中替代旧版的 Request.UserHostAddress)。
  • 本地与远端:HttpContext.Connection.LocalIpAddress / RemoteIpAddress。
  • 经过 Nginx 等反向代理时,RemoteIpAddress 会变成代理 IP,需要读取 X-Forwarded-For 请求头。

反向代理下的正确做法

在 Program 或 Startup 中启用 ForwardedHeaders 中间件(UseForwardedHeaders,配置 ForwardedHeaders.XForwardedFor | XForwardedProto),之后 RemoteIpAddress 即为真实客户端 IP。注意只信任已知代理,避免伪造请求头导致 IP 被冒用。

相关阅读

参考资料