简体   繁体   中英

Configure ASP.NET Core to work with proxy servers and load balancers

I have followed all steps explained on this Microsoft's documents page to be able to obtain remote client's IP address in an IIS-hosted app by calling HttpContext.Connection.RemoteIpAddress , but I keep getting the loopback IP address of ::1 . There is only one weird scenario that gets me the remote client's IP address and that's by the service configuration code below where ForwardedForHeaderName is initialized by X-Forwarded-For-Custom-Header-Name which does not make any sense to me!

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardLimit = 2;
    options.ForwardedForHeaderName = "X-Forwarded-For-Custom-Header-Name";
});

The full source code is found in this github repo and I'd like to know what exact change must be done to obtain the remote IP address successfully by removing "X-Forwarded-For-Custom-Header-Name" and why such a string gets me the IP address!

The idea is that X-Forwarded-For-Custom-Header-Name is meant to be replaced with a custom header name in case your proxy / load balancer doesn't use the standard X-Forwarded-For header but something different.

While X-Forwarded-For is the de-facto standard here, some proxies / load balancers use another header. In this case you would set it to the value used by your it, for examle X-Real-IP .

In your case, you will have to look at which headers are used in your setup and then configure your application accordingly.

When hosting in IIS using the default hosting model ( dotnet publish should generate the appropriate web.config file), the forwarding is already set up and handled by the IIS middleware.

Unless you expect proxy to forward the original IP address in a header that is different from the usual X-Forwarded-For you don't have to specify ForwardedForHeaderName , instead configure it as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM