【问题标题】:get real client ip address in dotnet core when using nginx使用 nginx 时在 dotnet core 中获取真实的客户端 IP 地址
【发布时间】:2019-05-29 03:32:13
【问题描述】:

我正在使用 dotnet 核心。我正在使用Request.HttpContext.Connection.RemoteIpAddress.ToString() 获取IP 地址。当我使用我的 IP 地址访问我的站点时,我看到客户端 IP 地址显示正确。但是我想使用 https 并且我使用 nginx。所以在我的位置我写了

    proxy_set_header  X-Real-IP $remote_addr;
    proxy_set_header  X-Forwarded-Proto https;
    proxy_set_header  X-Forwarded-For $remote_addr;
    proxy_set_header  X-Forwarded-Host $remote_addr;

当我通过域访问我的网站时,我的 ipaddress 显示为 ::1127.0.0.1(每次刷新时它们都会切换)。我的 nginx 配置在下面我不确定如何告诉 .net core 真实的 IP 地址


server {
    server_name         www.example.com;
    listen              443 ssl;
    ssl_certificate     /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
    root                /var/www/example.com/;
    add_header          Strict-Transport-Security "max-age=31536000";
    index index.html index.htm;
    log_not_found off;
    access_log off;
    #try_files $uri.html $uri $uri/ =404;
    expires max;
    default_type text/plain;
    include /etc/nginx/mime.types;

    index off;
    location ~/other/ {
        index off;
        autoindex on;
    }

    location /abc {
        proxy_pass http://localhost:5050;
        proxy_http_version 1.1;
        proxy_set_header  X-Real-IP $remote_addr;
        proxy_set_header  X-Forwarded-Proto https;
        proxy_set_header  X-Forwarded-For $remote_addr;
        proxy_set_header  X-Forwarded-Host $remote_addr;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

【问题讨论】:

    标签: nginx .net-core


    【解决方案1】:

    默认情况下不处理转发的标头。您需要使用 HttpOverrides 中间件。

    • Microsoft.AspNetCore.HttpOverrides 添加为依赖项
    • 将以下内容添加到您的 Configure 方法中:

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

    【讨论】:

    • 添加依赖后,您可以使用以下代码调用它: var ip = this.Request.Headers["X-Forwarded-For"].FirstOrDefault();if (ip.Contains(", ")) ip = ip.Split(',').First().Trim();
    • @ProjectMayhem 不!你不应该。相反,您应该使用Microsoft.AspNetCore.HttpOverrides,它会为您处理剩下的事情。
    【解决方案2】:

    我正在使用 .Net Core 2.2,发现以下工作。它与另一个答案(我无法工作)略有不同。

    • 添加 Microsoft.AspNetCore.HttpOverrides 作为依赖项
    • 将以下内容添加到 ConfigureServices 方法中:

     

    services.Configure<ForwardedHeadersOptions>(options =>
    {
        options.ForwardedHeaders =
            ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    });
    
    • 将以下内容添加到 Configure 方法中:

     

    app.UseForwardedHeaders();
    

    来源:Configure ASP.NET Core to work with proxy servers and load balancers

    【讨论】:

      最近更新 更多