Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserHostAddress in Asp.net Core

Tags:

asp.net-core

What is the equivalent in Asp.Net Core of the old HttpContext.Request.UserHostAddress?

I tried this.ActionContext.HttpContext but cannot find the UserHostAddress nor the ServerVariables properties.

Thanks

like image 386
Francesco Cristallo Avatar asked Nov 25 '14 17:11

Francesco Cristallo


People also ask

How do I get client IP address in asp net core?

Client IP address can be retrieved via HttpContext. Connection object. This properties exist in both Razor page model and ASP.NET MVC controller. Property RemoteIpAddress is the client IP address.

What is IHttpContextAccessor?

It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any. ASP.NET Core applications access the HTTPContext through the IHttpContextAccessor interface.


2 Answers

If you have access to the HttpContext, you can get the Local/Remote IpAddress from the Connection property like so:

var remote = this.HttpContext.Connection.RemoteIpAddress; var local = this.HttpContext.Connection.LocalIpAddress; 
like image 162
ry8806 Avatar answered Sep 21 '22 08:09

ry8806


This has moved since the original answer was posted. Access it now via

httpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress 
like image 43
kspearrin Avatar answered Sep 23 '22 08:09

kspearrin