在ASP.NET Core 2.2中获取客户端的IP地址

时间:2019-07-30 05:49:28

标签: c# asp.net-core dependency-injection microservices asp.net-core-webapi

我已经在asp.net core 2.2中创建了一个微服务应用程序。我想从他使用它的地方获取用户的IP地址。

下面的代码段提供了托管服务器的IP地址。

var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;

我想获取使用API​​进行审核日志的用户的IP地址。

2 个答案:

答案 0 :(得分:2)

注入IHttpContextAccessor

然后将以下代码段放入

var result = string.Empty;

 //first try to get IP address from the forwarded header
                if (_httpContextAccessor.HttpContext.Request.Headers != null)
                {
                    //the X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a client
                    //connecting to a web server through an HTTP proxy or load balancer

                    var forwardedHeader = _httpContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"];
                    if (!StringValues.IsNullOrEmpty(forwardedHeader))
                        result = forwardedHeader.FirstOrDefault();
                }

                //if this header not exists try get connection remote IP address
                if (string.IsNullOrEmpty(result) && _httpContextAccessor.HttpContext.Connection.RemoteIpAddress != null)
                    result = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

我认为这可能有用。

答案 1 :(得分:1)

请尝试在下面的行中获取呼叫者的IP地址。

HttpContext.Current.Request.UserHostAddress