Ask Your Question
4

What is the process for obtaining the client IP address in ASP.NET Core?

asked 2023-03-05 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-10-03 16:00:00 +0000

bukephalos gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-05 11:00:00 +0000

Seen: 11 times

Last updated: Oct 03 '22