There are a few steps involved in obtaining the client IP address in ASP.NET Core:
Inject the IHttpContextAccessor into the controller constructor using dependency injection in ASP.NET Core.
Access the HttpContext object through IHttpContextAccessor.HttpContext.
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.
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
Asked: 2023-03-05 11:00:00 +0000
Seen: 11 times
Last updated: Oct 03 '22
In ASP.NET 4.6, what is the alternative to PersistKeysToDbContext?
The ASP.NET Core MVC HTTP post method is receiving a null argument from an Angular call.
How can one obtain the hostBuilderContext while using WebApplication in ASP.NET Core 7?
What is the eventhandler for BackgroundService in ASP.NET Core and SignalR?
What is the method to separate radio buttons that are placed inside a table in ASP.NET MVC?
What is the method to utilize values from a yaml file in a json file using ASP.NET?
What is the problem that arises when generating a scaffolded item in ASP.NET Razor?
What is the procedure to reset/disable all items from IMemoryCache in ASP.NET Core?