在ASP.NET MVC应用程序中,可以使用HttpContext.Current.Request.UserHostAddress
来获取客户端IP地址。然而,这个方法获取的IP地址可能和其他IP检测工具(如whatismyipaddress.com)返回的IP地址不一样,这是因为前者默认返回的是X-Forwarded-For标头中指定的IP地址(如果有的话),而后者返回的是客户端的公共IP地址。
为了解决这个问题,可以使用以下代码来获取客户端真正的IP地址:
public static string GetUserIPAddress()
{
string ipAddress = null;
try
{
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
// The IP address is in the X-Forwarded-For header.
ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
// The IP address is not in the X-Forwarded-For header, so use the default behavior.
ipAddress = HttpContext.Current.Request.UserHostAddress;
}
}
catch (Exception ex)
{
// Log the error.
}
return ipAddress;
}
这段代码将先检查HTTP_X_FORWARDED_FOR
标头,如果有则认为是客户端的真正IP地址,否则使用默认行为获取客户端IP地址。