2023-04-12
333 0在.NET Core中,可以通过访问HttpContext中的RemoteIpAddress属性来获取请求者的IP地址。代码示例如下:
public IActionResult MyAction()
{
var remoteIpAddress = HttpContext.Connection.RemoteIpAddress;
return View();
}
需要注意的是,RemoteIpAddress属性返回的是一个IPAddress对象。如果你想要获取IP地址的字符串表示形式,可以调用ToString()方法:
var ipAddressString = HttpContext.Connection.RemoteIpAddress.ToString();
还需要注意的是,如果你的应用程序在反向代理后面运行,RemoteIpAddress属性返回的可能是代理服务器的IP地址,而不是最终请求的IP地址。在这种情况下,可以尝试从HTTP标头中获取客户端IP地址:
var remoteIpAddress = HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (string.IsNullOrEmpty(remoteIpAddress))
{
remoteIpAddress = HttpContext.Connection.RemoteIpAddress.ToString();
}
这里假设你使用的是X-Forwarded-For标头来传递客户端IP地址。如果你使用的是其他标头,请相应地修改代码。