gpt4 book ai didi

c# - Asp.net Core 获取客户端的远程 IP 总是返回 127.0.0.1

转载 作者:行者123 更新时间:2023-12-05 02:58:31 25 4
gpt4 key购买 nike

我的环境:Ubuntu 18.04、Asp.net Core 2.1、Nginx

我关注了this教程。我在 Startup.cs 中添加了这段代码:

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

我配置我的 Nginx 配置:

listen *:443 ssl http2;

location / {
proxy_pass https://localhost:6001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-Proto-Version $http2;
client_max_body_size 32m;
keepalive_timeout 200;
send_timeout 20;
client_body_timeout 50;
proxy_set_header X-Forwarded-For $remote_addr;
}

我通过以下方式获取远程 IP:

var ip = HttpContext.Connection.RemoteIpAddress?.ToString();

但它总是从任何 IP 返回 127.0.0.1。

最佳答案

我个人不得不手动获取 header 值。这是由于云设置。也许这会对您有所帮助。

if (Request.Headers.TryGetValue("X-Forwarded-For", out var forwardedIps))
senderIpv4 = forwardedIps.First();

关于c# - Asp.net Core 获取客户端的远程 IP 总是返回 127.0.0.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58970876/

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