从 SignalR 连接获取客户端 IP

Eli*_*ing 3 c# signalr .net-core asp.net-core

我知道这个问题之前已经被问过。但从那以后的大约 8 年里,SignalR 发生了很大的变化。

那么有人知道如何从 SignalR hub 获取客户端的 IP 吗?

我使用 SignalR 在不同服务器上的两个 .net core 应用程序之间进行通信,因此没有 HTTP 请求或服务网站或类似的东西。

Rom*_*syk 10

在您的中心内,您可以阅读IHttpConnectionFeature以下功能:

using Microsoft.AspNetCore.Http.Features;
...
var feature = Context.Features.Get<IHttpConnectionFeature>();
Run Code Online (Sandbox Code Playgroud)

IHttpConnectionFeature它将返回具有以下属性的实例:

public interface IHttpConnectionFeature
{
    //
    // Summary:
    //     The unique identifier for the connection the request was received on. This is
    //     primarily for diagnostic purposes.
    string ConnectionId { get; set; }
    //
    // Summary:
    //     The IPAddress of the client making the request. Note this may be for a proxy
    //     rather than the end user.
    IPAddress? RemoteIpAddress { get; set; }
    //
    // Summary:
    //     The local IPAddress on which the request was received.
    IPAddress? LocalIpAddress { get; set; }
    //
    // Summary:
    //     The remote port of the client making the request.
    int RemotePort { get; set; }
    //
    // Summary:
    //     The local port on which the request was received.
    int LocalPort { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

代码示例:

public override Task OnConnectedAsync()
{
     var feature = Context.Features.Get<IHttpConnectionFeature>();
     _logger.LogInformation("Client connected with IP {RemoteIpAddress}", feature.RemoteIpAddress);
     return base.OnConnectedAsync();
}
Run Code Online (Sandbox Code Playgroud)