获取客户端ip

Nginx中添加配置:

   location / {
       #保留代理之前的host 包含客户端真实的域名和端口号
       proxy_set_header    Host  $host; 
       #保留代理之前的真实客户端ip
       proxy_set_header    X-Real-IP  $remote_addr;  
       #这个Header和X-Real-IP类似,但它在多级代理时会包含真实客户端及中间每个代理服务器的IP
       proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
       #表示客户端真实的协议(http还是https)
       proxy_set_header X-Forwarded-Proto $scheme;
   }

中间件

 public class RemoteAddressMiddleware
    {
        private readonly ILogger<RemoteAddressMiddleware> _logger;
        private readonly RequestDelegate _next;

        public RemoteAddressMiddleware(RequestDelegate next, ILogger<RemoteAddressMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public Task Invoke(HttpContext context)
        {
            var headers = context.Request.Headers;
            try
            {
                if (headers.ContainsKey("X-Forwarded-For"))
                    context.Connection.RemoteIpAddress = IPAddress.Parse(headers["X-Forwarded-For"].ToString()
                        .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[0]);
                if (headers.ContainsKey("X-Forwarded-Proto"))
                    context.Request.Scheme = headers["X-Forwarded-Proto"].ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Handle RemoteAddress Error!MSG:{ex.StackTrace}");
            }
            return _next(context);
        }
    }

添加中间件

app.UseMiddleware<RemoteAddressMiddleware>();

 

posted @ 2023-04-17 16:24  向萧  阅读(10)  评论(0编辑  收藏  举报