c# - 在 ASP.NET 中获取客户端 IP 地址
问题描述
如何获取客户端的 IP 地址?当我使用时,HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]
我得到类似 [::1]:12473
当我使用时,HttpContext.Current.Request.UserHostAddress
我不断得到::1
解决方案
当您在本地运行代码时,您将获得 ::1 (localhost)。如果您发布到 Azure,您应该获得正确的 IP 地址。
您也可以通过检查 HTTP_X_FORWARDED_FOR 标头来扩展您的代码。当涉及代理和/或负载平衡器时,这将返回正确的客户端 IP 地址。
string ipAddress = HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
{
ipAddress = HttpContext.Request.ServerVariables["REMOTE_ADDR"];
}
推荐阅读
- python - 在 python 3.6 中使用 UTC 偏移量解析日期时间
- javascript - CSP 通过传递 PHP 变量转换内联 onclick 事件
- java - ListView 不刷新数据库中的内容
- javascript - Swift iOS 13 推送通知设备令牌在 javascript/php/typescript 中转换
- python - 如何将所有 tf.data.Dataset 对象提取为特征和标签并传递给 ImageDataGenerator 的 flow() 方法?
- java - 如何从列表中收集多个列表
通过使用 java 8 流? - perl - perl 5.8.4 脚本可以与 perl 5.16.3 一起使用吗?
- html - 文本框文本隐藏浮动标签文本框样式
- fortran - 双精度函数 wp(S,wmav,ip)
- keycloak - Keycloak Gatekeeper 始终无法验证“iss”声明值