欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

关于.net core使用nginx做反向代理获取客户端ip的问题

程序员文章站 2022-06-25 08:16:03
1、正常情况下.net core获取客户端ip是比较简单的 通过这样一个方法就能获取到客户端ip。 2、但是,我在centos下使用nginx代理后,这样指向的就是本地ip了,所以需要将nginx获取到的ip传递到.net core web站点。 3、首先,我们需要在Startup.cs里添加 然后 ......

1、正常情况下.net core获取客户端ip是比较简单的

         /// <summary>
        /// 获取客户ip
        /// </summary>
        /// <param name = "context" ></ param >
        /// < returns ></ returns >
        public static string getclientuserip(this httpcontext context)
        {
            var ip = context.request.headers["x-forwarded-for"].firstordefault();
            if (string.isnullorempty(ip))
            {
                ip = context.connection.remoteipaddress.tostring();
            }

            return ip;
        }    

  通过这样一个方法就能获取到客户端ip。

2、但是,我在centos下使用nginx代理后,这样指向的就是本地ip了,所以需要将nginx获取到的ip传递到.net core web站点。

3、首先,我们需要在startup.cs里添加

app.useforwardedheaders(new forwardedheadersoptions
            {
                forwardedheaders = forwardedheaders.xforwardedfor | forwardedheaders.xforwardedproto
            });

然后

server {
    listen 80;
    location / {
        proxy_pass http://localhost: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;
    }
}

这是之前我的nginx配置。

需要再加上一行

roxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;

最后重启nginx,至此可以获取到客户端ip啦。