Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Client IP address in ASP.NET Core 2.1

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'

enter image description here

enter image description here

Can you please let me know how to get client IP address in ASP.NET Core 2.1.

like image 586
Ahmer Ali Ahsan Avatar asked Jun 30 '18 15:06

Ahmer Ali Ahsan


1 Answers

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" }; } 
like image 81
zdub Avatar answered Sep 21 '22 02:09

zdub