get real client ip address in dotnet core when usi

2020-07-14 05:39发布

I'm using dotnet core. I'm grabbing the IP address using the line Request.HttpContext.Connection.RemoteIpAddress.ToString(). When I visit my site using my ip address I see the client ip address showing correctly. However I want to use https and I use nginx. So in my location I wrote

    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;

When I visit my site through the domain my ipaddress shows as ::1 and 127.0.0.1 (they switch every time I refresh). My nginx config is below I'm not exactly sure how to tell .net core the real ip address


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;
    }
}

2条回答
放我归山
2楼-- · 2020-07-14 06:15

Forwarded headers are not processed by default. You need to use HttpOverrides middleware.

  • add Microsoft.AspNetCore.HttpOverrides as dependency
  • add the following to your Configure method:

    app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor |
            ForwardedHeaders.XForwardedProto
        }); 
    
查看更多
放荡不羁爱自由
3楼-- · 2020-07-14 06:22

I am using .Net Core 2.2, and found the following to work. It's slightly different than the other answer (which I couldn't get to work).

  • Add Microsoft.AspNetCore.HttpOverrides as dependency
  • Add the following to the ConfigureServices method:

 

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
  • Add the following to the Configure method:

 

app.UseForwardedHeaders();

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

查看更多
登录 后发表回答