Get a users remote IP Address in ASP.Net Core

Posted by Blake on 6/4/2017
)

Issue

You want to obtain the IP address of the user who is accessing your site in an ASP.Net Core website.

Resolution:

In ASP.Net Core you can still obtain remote IP address from the HttpContext but it has moved locations from older iterations of MVC/Webforms. If you are in a controller you can access it with a single line (the HttpContext exists in controllers by default, if you are not in a controller you can still access this but you will need to inject the HttpContext).

C#

    // As a string
    string ipString = HttpContext.Connection.RemoteIpAddress.ToString();

    // As the IpAddress object
    System.Net.IPAddress ipAddress = HttpContext.Connection.RemoteIpAddress;