环境 centos,docker,nginx,.net 5
1. 配置Nginx
server {
listen 80;
server_name www.xxx.cn;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr; #为防止Ip伪造 如多个代理在最外层设置 remote_addr 其他代理设置$proxy_add_x_forwarded_for;
proxy_pass http://localhost:xxx/;
}
error_page 500 502 503 504 /50x.html;
}
修改完成后nginx -s reload 重新加载配置文件
2. 代码添加配置
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
3. 使用原始方法获取IP地址
var ip = context.HttpContext.Connection.RemoteIpAddress.ToString()