.NET core ABP obtain remote IP address

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 RemoteIpAddressis the type of IPAddressnot string. It includes IPv4, IPv6, and other information, it is not like classic ASP.NET, the more we use it. 

Guess you like

Origin www.cnblogs.com/topguntopgun/p/11008278.html