Obtain client IP when using load balancing in ASP.NET Core

In the case of load balancing, the IP address of the load balancing is obtained through context.Connection.RemoteIpAddress, and the real IP of the client needs to be obtained through the X-Forwarded-For request header.

The previous method is to directly obtain the X-Forwarded-For request header by yourself, the code is as follows:

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;
    }
}

Now use the built-in Forwarded Headers Middleware of asp.net core to achieve.

First configure ForwardedHeadersOptions in Startup.ConfigureServices, and only need to specify ForwardedHeaders.XForwardedFor for the scenario of obtaining the client IP.

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

Note 1: If the load balancing is not forwarding requests through the Loopback address on the local machine, options.KnownNetworks.Clear and options.KnownProxies.Clear must be added.

Note 2: If the environment variable ASPNETCORE_FORWARDEDHEADERS_ENABLED is set to true, the above configuration code is not needed.

Then add Forwarded Headers middleware in Startup.Configure.

app.UseForwardedHeaders()

In this way, the real IP address of the client can be obtained through RemoteIpAddress.

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

Guess you like

Origin blog.csdn.net/qianjiu/article/details/121996186