58

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

Francesco Cristallo
  • 2,856
  • 5
  • 28
  • 57
  • 1
    Does this answer your question? [How do I get client IP address in ASP.NET CORE?](https://stackoverflow.com/questions/28664686/how-do-i-get-client-ip-address-in-asp-net-core) – Magnetron Aug 10 '21 at 18:09

4 Answers4

57

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;
ry8806
  • 2,258
  • 1
  • 23
  • 32
17

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

httpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress
kspearrin
  • 10,238
  • 9
  • 53
  • 82
15

HttpRequest.UserHostAddress gives the IP address of the remote client. In ASP.NET Core 1.0, you have to use the HTTP connection feature to get the same. HttpContext has the GetFeature<T> method that you can use to get a specific feature. As an example, if you want to retrieve the remote IP address from a controller action method, you can do something like this.

var connectionFeature = Context
           .GetFeature<Microsoft.AspNet.HttpFeature.IHttpConnectionFeature>();

if (connectionFeature != null)
{
    string ip = connectionFeature.RemoteIpAddress.ToString();
}
Florian Schaal
  • 2,586
  • 3
  • 39
  • 59
  • Thank you very much this works, I would have never arrived to this myself. Where I could find a documentation o some reference? I`m also searching the old HttpContext.Request.ServerVariables["X_FORWARDED_FOR"]; Do you know what is the new syntax to this? Thanks! – Francesco Cristallo Nov 25 '14 at 18:01
  • 2
    This appears to not work correctly when running in IIS 8. The IP address returned in the code is different than what IIS outputs in the request log. Any updates to this that would allow it to work properly in IIS? – Stephen Watkins Jan 28 '15 at 16:49
0

For aspnet rc1-update1 I found IP(with port) in X-Forwarded-For header, which's value can be accessed from controller as HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault().

FLCL
  • 2,445
  • 2
  • 24
  • 45
  • 4
    This header is typically only present if the request went through a load balancer (or something similar) to add the original address. – David De Sloovere Jan 20 '18 at 13:56