HttpContext.Connection.RemoteIpAddress返回kubernetes中www.example.com核心的私有地址asp.net

xmq68pz9  于 2023-02-11  发布在  Kubernetes
关注(0)|答案(1)|浏览(93)

我有一个asp.net核心7.0 API应用程序,它位于Nginx入口控制器后面的Kubernetes中的Docker容器中。
要获取我正在使用的客户端IP地址
context.HttpContext.Connection.RemoteIpAddress
对于所有用户请求,我得到一个私有IP地址,如“10.244.0.1”
在这种情况下,我期待公共IP地址

gdrx4gfi

gdrx4gfi1#

您需要配置nginx来转发X-Forwarded-ForX-Forwarded-Proto报头。

server {
    listen        80;
    server_name   example.com *.example.com;
    location / {
        proxy_pass         http://127.0.0.1:5000;
        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-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

然后设置UseForwardedHeaders中间件,该中间件将使用X-Forwarded-For头值更新HttpContext.Connection.RemoteIpAddress

var builder = WebApplication.CreateBuilder(args);

// ...
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

var app = builder.Build();

app.UseForwardedHeaders();

// ...

检查:配置ASP.NET核心以使用代理服务器和负载平衡器

相关问题