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

问题描述

我有一张桌子:有模型

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 格式