Get client IP address

Earlier in another version of asp.net, I used these HttpRequest properties:

 Request.ServerVariables["REMOTE_ADDR"] Request.UserHostAddress 

How can I achieve the same in the ASP.NET kernel?

+8
source share
5 answers

You can use IHttpContextAccessor :

 private IHttpContextAccessor _accessor; public Foo(IHttpContextAccessor accessor) { _accessor = accessor; } 

Now you get the IP address this way "

 var ip = _accessor.HttpContext.Connection.RemoteIpAddress.ToString(); 
+9
source

HttpContext.Connection.RemoteIpAddress is the property you are looking for

+8
source

And you can use Request

 var GetIp = Request.HttpContext.Connection.RemoteIpAddress.ToString(); 
0
source

It works very well.

 var ip = request.HttpContext.Connection.RemoteIpAddress; 
0
source

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.

0
source

All Articles