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

3
我已经使用ASP.NET Core 2.2创建了一个微服务应用程序,现在想获取用户使用该应用程序的IP地址。
以下代码片段提供了托管服务器的IP地址。
var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;

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

我认为你需要将它从客户端传递到服务器(Web API)。 - jazb
2
如果您正在托管Web API并在同一台机器上调用Web API,则将看到用request.HttpContext.Connection.RemoteIpAddress表示的相同IP地址。 - Chetan
@JohnB,你能否提供给我步骤或示例? - TrinTrin
1个回答

3

注入 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();

我认为它可能会起作用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接