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

标签 c# nginx asp.net-core

我的环境: 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/

相关文章:

c# - Asp.NET MVC/Web API 的模式满足 SignalR/Websockets

c# - 在 asp.net 应用程序中将今天的日期存储为静态值有什么缺点吗?

asp.net-mvc - IFormFile - 最大文件大小的属性(以兆字节为单位)

c# - 无法使用HttpClient获取API资源

c# - 指针从 C# 代码到 VB.net 的问题转换

c# - 使用 Microsoft.Azure.EventHubs 创建多个重用相同底层 TCP 连接的 EventHubClient 对象

apache - 更改 Apache .htaccess 文件以与 Nginx 一起使用

mod-rewrite - k8s nginx 入口重写目标注释未按预期工作

codeigniter - fsockopen() : unable to connect to ssl://smtp. gmail.com:465(权限被拒绝)

linux - 自动化 Azure 资源部署的行业标准方法