Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Core get remote IP of client always returns 127.0.0.1

My environment: Ubuntu 18.04, Asp.net Core 2.1, Nginx

I followed this tutorial. I added this code in Startup.cs:

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

I configure my Nginx configuration:

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

I get the remote IP by:

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

but it always returns 127.0.0.1 from any IP.

like image 526
Erics Nguyen Avatar asked Oct 14 '25 18:10

Erics Nguyen


2 Answers

I personally had to get header value manually. It was due to the cloud setting. Maybe this will help you.

if (Request.Headers.TryGetValue("X-Forwarded-For", out var forwardedIps))
    senderIpv4 = forwardedIps.First();
like image 174
Morasiu Avatar answered Oct 17 '25 12:10

Morasiu


You forgot proxy_set_header X-Forwarded-Proto $scheme; in your nginx configuration.

like image 24
pinki Avatar answered Oct 17 '25 12:10

pinki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!