In classic ASP.NET we used to get client IP Address by Request.UserHostAddress. But this does not apply to ASP.NET Core 2.0. We need a different way to retrieve HTTP Request information.

1. Define a variable in your MVC controller

private IHttpContextAccessor _accessor;

2.  DI into the controller's constructor

public SomeController(IHttpContextAccessor accessor)
    _accessor = accessor;

3. Retrive the IP Address


This is how it is done.

If your ASP.NET Core project is created with the default MVC template, you should have the DI for HttpContextAcccessor in Startup.cs

public void ConfigureServices(IServiceCollection services)
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

2018/9/28 Update:

In ASP.NET 2.1, you can do this instead:

services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();

The RemoteIpAddress is in type of IPAddress, not string. It contains IPv4, IPv6 and other information, it is not like the classic ASP.NET, which will be more useful to us. 

If you want to access this information in Razor Views (cshtml). Just use @inject to DI into the view:

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor

and then use it in your razor page:

Client IP: @HttpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString()