Asp.net Core Remote IP Address get local ip (192.168.1.1)

1.3k Views Asked by At

I am getting IP address by following code:

var remoteIpAddress = HttpContext?.Connection?.RemoteIpAddress?.ToString ();

This is working okay when I am running on IIS with accessing by IP address (public IP address of my ISP network).

I host on another server but mapping to domain name (cannot be accessed by IP due to multiple website hosting on IIS).

It is working fine just not getting the remote IP address of client acceessing.

Also, I try the following code recommended by Microsoft but it is not working.

  services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = 
                    ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });
1

There are 1 best solutions below

10
S. Zahir On

Here is a solution to get client IP address in ASP.NET Core.

Inject the HttpContextAccessor instance in the ConfigureServices method from the Startup.cs class. Now add this reference using Microsoft.AspNetCore.Http.

public void ConfigureServices(IServiceCollection services)
    {
         services.AddControllersWithViews();
         services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    }

Declare a variable.

private readonly IActionContextAccessor _accessor;

Update the HomeController to inject the IActionContextAccessor in the constructor. try to inject the IActionContextAccessor into the controller’s constructor with DI.

public HomeController(ILogger logger, IActionContextAccessor accessor)
{
    _logger = logger;
    _accessor = accessor;
}

Now at last step try to retrieve the IP address from the accessor variable.

public IActionResult Index()
{
  var ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.ToString();
  return View();
}

If you don not want to use DI, you can always access the IP information directly in the controller as followed.

var ip = HttpContext.Connection.RemoteIpAddress.ToString();