UserHostAddress in Core Asp.net

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

I tried this. this.ActionContext.HttpContext but cannot find either UserHostAddress or ServerVariables properties.

thank

+23
asp.net-core
Nov 25 '14 at 17:22
source share
4 answers

This has changed since the publication of the original answer. Access it through

 httpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress 
+13
Feb 02 '16 at 3:43
source share

If you have access to the HttpContext , you can get the local / remote IpAddress from the Connection property as follows:

 var remote = this.HttpContext.Connection.RemoteIpAddress; var local = this.HttpContext.Connection.LocalIpAddress; 
+14
Jun 16 '17 at 13:21
source share

HttpRequest.UserHostAddress gives the IP address of the remote client. In ASP.NET Core 1.0, you need to use the HTTP connection function to get the same thing. HttpContext has a GetFeature<T> method that can be used to get a specific function. For example, if you want to get the remote IP address from the 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(); } 
+12
Nov 25 '14 at 17:41
source share

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

0
Mar 09 '16 at 10:37
source share



All Articles