简体   繁体   中英

Getting Ip from DefaultHubCallerContext behind a load balancer

I have a.Net 5 app with a SignalR hub and i want to get the client's IP from the "X-forwarded-for". My app is behind a load balancer so getting the RemoteIpAddress always returns a 10.xxx Ip.

Starting with HubCallerContext i can get a IHttpConnectionFeature from its features

var httpReq = Context.Features.Get<IHttpConnectionFeature>();

And when debugging i can see that the object contains a RequestHeader , but i can only access LocalIpAddress , RemoteIpAddress , LocalPort , and ConnectionId .

Calling httpReq.RequestHeaders does not let me compile the app.

Is there any way of getting the headers from either the IHttpConnectionFeature or DefaultHubCallerContext ?

You can use the middleware IApplicationBuilder#UseForwardedHeaders from Microsoft.AspNetCore.Builder.ForwardedHeadersExtensions .

This middleware updates RemoteIpAddress to the client's IP, as long all proxies update correctly the header X-Forwarded-For and that the options are correct (We have to either hardcode the number of proxies or tell the IP/network that we can trust).

In your Startup.cs add the following middleware to the Configure method:

app.UseForwardedHeaders();

Then in ConfigureServices you have to configure it:

services.Configure<ForwardedHeadersOptions>(options =>
{
 ...
});

More information about the options and this in: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-6.0#forwarded-headers-middleware-options

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