In classic ASP.NET, we used to obtain the client IP address by Request.UserHostAddress . But this does not apply to ASP.NET Core 2.0. We need another way to get the HTTP request information.
Define a variable in your MVC
private IHttpContextAccessor _accessor;
DI to controller constructor
public SomeController(IHttpContextAccessor accessor) { _accessor = accessor; }
Get IP Address
_accessor.HttpContext.Connection.RemoteIpAddress.ToString()
If your main ASP.NET project is created with the default MVC template, you must have a DI for the HttpContextAcccessor in Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); } services.AddHttpContextAccessor(); services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
RemoteIpAddress is of type IPAddress, not a string. Contains IPv4, IPv6, and other information.
source share