在 ASP.NET Core 中获取客户端真实IP地址需要使用HttpContext对象。可以使用以下代码示例:
if (HttpContext.Connection.RemoteIpAddress != null)
{
var ip = HttpContext.Connection.RemoteIpAddress.ToString();
if (ip.Contains(":"))
{
ip = ip.Substring(0, ip.IndexOf(":"));
}
}
在这个示例中,我们检查 Connection.RemoteIpAddress 是否为null,如果它不是null,我们就获取它的string表示形式。如果它包含“:”(这是一个IPv6地址的常见格式),我们就截取它的前半部分,这样我们就只保留了IPv4地址。