ASP .NET Core:获取用户 IP 地址

ASP .NET Core: Get User IP Address

我有一个 table : 有一个模型

public class ArticleLike:BaseEntity
{
    public long? UserId { get; set; }
    public string UserIp { get; set; }
    public ICollection<User> User { get; set; }
}

如何获取用户的IP地址? 我必须在服务或存储库上编写它的方法吗?

var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;

var remoteIpAddress = httpContext.GetFeature<IHttpConnectionFeature>()?.RemoteIpAddress;

简单用法:

在控制器中

public class HomeController : Controller
{
private readonly IHttpContextAccessor _httpContextAccessor;

public HomeController(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

public IActionResult Index()
{
    var ip = _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
    return Content(ip);
}

}

在启动文件中:

public void ConfigureServices(IServiceCollection services)
{
   services.AddHttpContextAccessor();
}    

获取客户​​端用户IP地址

var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();

可以通过 HttpContext.Connection 对象检索客户端 IP 地址。

属性 RemoteIpAddress 是客户端IP地址。返回的对象(System.Net.IpAddress)可以用来判断是IPV4地址还是IPV6地址。

例如,如果您得到像 ::1 这样的结果,这就是 IPv6 格式