I'm working on ASP.Net Core 2.1 with Angular Template provided by Microsoft Visual Studio 2017. My Client App is working fine. After competition of User Authentication, I want to start User Session Management in which I store client user IP Address. I've already searched for this on the internet but so far not found any solution.
Below are some ref links which I already visited:
How do I get client IP address in ASP.NET CORE?
Get Client IP Address in ASP.NET Core 2.0
Get a user remote IP Address in ASP.Net Core
In my ValuesController.cs I also tried below code:
private IHttpContextAccessor _accessor; public ValuesController(IHttpContextAccessor accessor) { _accessor = accessor; } public IEnumerable<string> Get() { var ip = Request.HttpContext.Connection.RemoteIpAddress.ToString(); return new string[] { ip, "value2" }; } wherein ip variable I get null value and getting this error
Request.HttpContext.Connection.RemoteIpAddress.Address threw an exception of Type 'System.Net.Sockets.SocketException'


Can you please let me know how to get client IP address in ASP.NET Core 2.1.
In your Startup.cs, make sure you have a method to ConfigureServices, passing in the IServiceCollection, then register IHttpContextAccessor as a singleton as follows:
public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); } After registering the IHttpContextAccessor in your Startup.cs file, you can inject the IHttpContextAccessor in your controller class and use it like so:
private IHttpContextAccessor _accessor; public ValuesController(IHttpContextAccessor accessor) { _accessor = accessor; } public IEnumerable<string> Get() { var ip = _accessor.HttpContext?.Connection?.RemoteIpAddress?.ToString(); return new string[] { ip, "value2" }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With