You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6下SignalR TCP客户端IP获取及访问控制问题

在.NET 6 SignalR TCP托管中限制特定IP连接的解决方案

获取客户端IP地址的正确方式

在TCP托管场景下,IHttpConnectionFeature仅适用于HTTP上下文,因此无法获取IP。你可以改用Kestrel提供的IConnectionRemoteIpAddressFeature来获取远程客户端IP:

var remoteIpFeature = Context.Features.Get<IConnectionRemoteIpAddressFeature>();
var clientIp = remoteIpFeature?.RemoteIpAddress?.MapToIPv4().ToString();

MapToIPv4()用于统一IPv6和IPv4格式,避免因地址类型不同导致的验证失败。

实现动态IP权限验证

在Hub的OnConnectedAsync方法中加入IP校验逻辑,对接数据库判定权限,不符合条件则直接断开连接:

private readonly IIpPermissionService _ipPermissionService;

// 通过构造函数注入数据库查询服务
public YourHub(IIpPermissionService ipPermissionService)
{
    _ipPermissionService = ipPermissionService;
}

public override async Task OnConnectedAsync()
{
    var remoteIpFeature = Context.Features.Get<IConnectionRemoteIpAddressFeature>();
    if (remoteIpFeature?.RemoteIpAddress == null)
    {
        // 无法获取IP时直接拒绝连接
        await Context.AbortAsync();
        return;
    }

    var clientIp = remoteIpFeature.RemoteIpAddress.MapToIPv4().ToString();
    var allowedIps = await _ipPermissionService.GetAllowedIpsAsync();

    if (!allowedIps.Contains(clientIp))
    {
        await Context.AbortAsync();
        return;
    }

    await base.OnConnectedAsync();
}

是否需要放弃SignalR TCP托管?

不需要。上述方案完全满足你的需求:通过Kestrel原生特性获取IP,结合数据库动态校验权限,无需依赖防火墙规则。SignalR的TCP托管模式本身支持这类自定义连接验证场景,无需切换到其他TCP框架。

内容的提问来源于stack exchange,提问作者Inf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 08:27:39