gpt4 book ai didi

c# - 从 SignalR 连接获取客户端 IP

转载 作者:行者123 更新时间:2023-12-05 01:08:08 24 4
gpt4 key购买 nike

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

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

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

最佳答案

在您的集线器中,您可以阅读 IHttpConnectionFeature 功能,例如:

using Microsoft.AspNetCore.Http.Features;
...
var feature = Context.Features.Get<IHttpConnectionFeature>();

它将返回具有以下属性的 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; }
}

代码示例:

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

关于c# - 从 SignalR 连接获取客户端 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66448666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com