ASP.NET Core 中使用负载均衡时获取客户端 IP

在使用负载均衡的情况下,通过 context.Connection.RemoteIpAddress 获取到的是负载均衡的 IP 地址,需要通过 X-Forwarded-For 请求头才能获取到客户端的真实 IP 。

之前采用的方式是自己直接获取 X-Forwarded-For 请求头,代码如下:

public static class HttpContextExtensions
{
    public static string GetUserIp(this HttpContext context)
    {
        var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
        if (string.IsNullOrEmpty(ip))
        {
            ip = context.Connection.RemoteIpAddress?.ToString();
        }
        return GetSingleIP(ip);
    }

    private static string GetSingleIP(string ip)
    {
        if (!string.IsNullOrEmpty(ip))
        {
            var commaIndex = ip.LastIndexOf(",");
            if (commaIndex >= 0)
            {
                ip = ip.Substring(commaIndex + 1);
            }
        }
        return ip;
    }
}

现在改用 asp.net core 内置的 Forwarded Headers Middleware 来实现。

先在 Startup.ConfigureServices 中配置 ForwardedHeadersOptions ,对于获取客户端 IP 的场景只需要指定 ForwardedHeaders.XForwardedFor 。

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.KnownNetworks.Clear();
    options.KnownProxies.Clear();
});

注:如果负载均衡不是在本机通过 Loopback 地址转发请求的,一定要加上 options.KnownNetworks.Clear 与 options.KnownProxies.Clear 。

然后在 Startup.Configure 中添加 Forwarded Headers 中间件。

app.UseForwardedHeaders()

这样就可以通过 RemoteIpAddress 获取客户端的真实  IP 地址了。

var ip = Request.HttpContext.Connection.RemoteIpAddress?.MapToIPv4().ToString();

转载于:https://www.cnblogs.com/dudu/p/11088645.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值