Search code examples
databaseasp.net-coregetipip-address

ASP .NET Core: Get User IP Address


I have a table : with a model

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

How can I get Ipaddress of user ? I had to write method of it on service or repository?


Solution

  • Get client user IP address

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

    Client IP address can be retrieved via HttpContext.Connection object.

    Property RemoteIpAddress is the client IP address. The returned object (System.Net.IpAddress) can be used to check whether it is IPV4 or IPV6 address.

    For example, if you get a result like ::1, this is the IPv6 format