gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:51:31 26 4
gpt4 key购买 nike

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

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

var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;

我想获取将 API 用于审核日志目的的用户的 IP 地址。

最佳答案

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

我认为它可能会起作用。

关于c# - 在 ASP.NET Core 2.2 中获取客户端的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57265063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com