首页 > 解决方案 > 在 ASP.NET 中获取客户端 IP 地址

问题描述

如何获取客户端的 IP 地址?当我使用时,HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]我得到类似 [::1]:12473

当我使用时,HttpContext.Current.Request.UserHostAddress我不断得到::1

标签: c#asp.nethttp

解决方案


当您在本地运行代码时,您将获得 ::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"];
}

推荐阅读