2, asp.net arranged on the core 2.x
The first step: define variables in the controller
private IHttpContextAccessor _accessor;
Step Two: implanting controller constructor
public ValuesController(IHttpContextAccessor accessor) { _accessor = accessor; }
The third step: calling in the action
_accessor.HttpContext.Connection.RemoteIpAddress.ToString()
Step four: we should configure the IHttpContextAccessor in startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); }
Step Five: You can run the test:
It has been found to obtain an IP address it.
Note: In ASP.NET 2.1, the startup.cs need to be modified to the following content:
services.AddHttpContextAccessor(); services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
This RemoteIpAddress
is the type of IPAddress
not string
. It includes IPv4, IPv6, and other information, it is not like classic ASP.NET, the more we use it.