英文:
HttpContext.Connection.RemoteIpAddress returns private address for asp.net core in kubernetes
问题
我有一个在Kubernetes中托管的Docker容器中的asp.net core 7.0 API应用程序,后面是一个Nginx Ingress控制器。
为了获取客户端IP地址,我正在使用以下代码:
context.HttpContext.Connection.RemoteIpAddress
对于所有用户请求,我得到一个私有IP地址,如'10.244.0.1'。
在这种情况下,我期望公共IP地址。
英文:
I have an asp.net core 7.0 api application in a docker container hosted in Kubernetes behind an Nginx ingress controller.
To get the client ip address i'm using
> context.HttpContext.Connection.RemoteIpAddress
for all user requests I get a Private Ip address like '10.244.0.1'
In such instances i'm expecting Public IP address
答案1
得分: 4
你需要配置nginx以转发X-Forwarded-For
和X-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 Core以与代理服务器和负载均衡器一起工作。
英文:
You need to configure nginx to forward the X-Forwarded-For
and X-Forwarded-Proto
headers. Example:
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;
}
}
Then setup the UseForwardedHeaders
middleware. This middleware will update HttpContext.Connection.RemoteIpAddress
using the X-Forwarded-For
header value.
var builder = WebApplication.CreateBuilder(args);
// ...
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
var app = builder.Build();
app.UseForwardedHeaders();
// ...
Check: Configure ASP.NET Core to work with proxy servers and load balancers
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论