UserHostAddress in Asp.net Core

后端 未结 4 1019
挽巷
挽巷 2020-12-13 17:50

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

I tried this.ActionContext.HttpContext but cannot fi

相关标签:
4条回答
  • 2020-12-13 18:08

    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();
    }
    
    0 讨论(0)
  • 2020-12-13 18:21

    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;
    
    0 讨论(0)
  • 2020-12-13 18:24

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

    httpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress
    
    0 讨论(0)
  • 2020-12-13 18:29

    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().

    0 讨论(0)
提交回复
热议问题