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>();
标签:Forwarded,获取,ip,next,headers,proxy,logger,客户端 From: https://www.cnblogs.com/dayang12525/p/17326283.html