Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are a few steps involved in obtaining the client IP address in ASP.NET Core:

  1. Inject the IHttpContextAccessor into the controller constructor using dependency injection in ASP.NET Core.

  2. Access the HttpContext object through IHttpContextAccessor.HttpContext.

  3. Use HttpContext.Connection.RemoteIpAddress to get the IP address of the client.

Example code:

private readonly IHttpContextAccessor _httpContextAccessor;

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

public IActionResult YourAction()
{
    var ipAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress;
    // Do something with the IP address
}

Note: The RemoteIpAddress property will return an IPAddress object, which you can convert to a string using the ToString() method.