[英]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".我有一个带有 SignalR 集线器的.Net 5 应用程序,我想从“X-forwarded-for”获取客户端的 IP。 My app is behind a load balancer so getting the RemoteIpAddress always returns a 10.xxx Ip.
我的应用程序位于负载均衡器后面,因此获取 RemoteIpAddress 始终返回 10.xxx Ip。
Starting with HubCallerContext i can get a IHttpConnectionFeature from its features从 HubCallerContext 开始,我可以从其功能中获取 IHttpConnectionFeature
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
.调试时我可以看到 object 包含一个
RequestHeader
,但我只能访问LocalIpAddress
、 RemoteIpAddress
、 LocalPort
和ConnectionId
。
Calling httpReq.RequestHeaders
does not let me compile the app.调用
httpReq.RequestHeaders
不会让我编译应用程序。
Is there any way of getting the headers from either the IHttpConnectionFeature
or DefaultHubCallerContext
?有什么方法可以从
IHttpConnectionFeature
或DefaultHubCallerContext
获取标头?
You can use the middleware IApplicationBuilder#UseForwardedHeaders
from Microsoft.AspNetCore.Builder.ForwardedHeadersExtensions
.您可以使用来自
Microsoft.AspNetCore.Builder.ForwardedHeadersExtensions
的中间件IApplicationBuilder#UseForwardedHeaders
。
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).此中间件将
RemoteIpAddress
更新为客户端的 IP,只要所有代理正确更新 header X-Forwarded-For
并且选项正确(我们必须硬编码代理的数量或告诉我们可以信任的 IP/网络)。
In your Startup.cs
add the following middleware to the Configure
method:在您的
Startup.cs
中,将以下中间件添加到Configure
方法中:
app.UseForwardedHeaders();
Then in ConfigureServices
you have to configure it:然后在
ConfigureServices
中,您必须对其进行配置:
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有关选项的更多信息,请参见: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-6.0#forwarded-headers-middleware -选项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.