如何在SignalR .NET客户端获取连接的TransportType?
在SignalR .NET客户端获取当前使用的传输机制
要在基于Microsoft.AspNetCore.SignalR.Client的.NET客户端中获取当前连接的传输类型,可通过以下方式实现:
首先确保引用必要的命名空间:
using Microsoft.AspNetCore.SignalR.Client; using Microsoft.AspNetCore.Connections.Features;创建并启动HubConnection后,通过
HubConnection的Features属性获取IConnectionTransportFeature实例,从中提取传输类型:// 构建Hub连接 var hubConnection = new HubConnectionBuilder() .WithUrl("你的Hub服务地址") .Build(); // 启动连接 await hubConnection.StartAsync(); // 获取当前传输机制 var transportFeature = hubConnection.Features.Get<IConnectionTransportFeature>(); if (transportFeature != null) { // TransportType枚举包含WebSockets、ServerSentEvents、LongPolling等取值 var currentTransport = transportFeature.TransportType; // 用于调试输出 Console.WriteLine($"当前使用的传输机制:{currentTransport}"); }也可以通过监听连接状态变化事件,在连接成功后自动获取传输类型(适合需要实时监控的场景):
hubConnection.StateChanged += (stateChange) => { if (stateChange.NewState == HubConnectionState.Connected) { var transportFeature = hubConnection.Features.Get<IConnectionTransportFeature>(); if (transportFeature != null) { Console.WriteLine($"连接已建立,当前传输机制:{transportFeature.TransportType}"); } } }; await hubConnection.StartAsync();
该方法适用于ASP.NET Core 3.1及以上版本的SignalR客户端,能直接在客户端获取当前生效的传输类型,满足调试网络问题的需求。
内容的提问来源于stack exchange,提问作者ProbablePrime
相关产品推荐
相关产品推荐

