连接Azure SignalR时出现'blazorpack'键不存在的字典异常问题
连接Azure SignalR服务时出现KeyNotFoundException(键'blazorpack'不存在)的解决方法
问题描述
使用Azure SignalR服务替代原生SignalR时,抛出System.Collections.Generic.KeyNotFoundException: 给定的键 'blazorpack' 不存在于字典中异常,但使用普通SignalR服务时一切正常,控制台无错误提示且SignalR连接成功。
服务配置代码
services.AddRazorComponents().AddInteractiveServerComponents() .AddCircuitOptions(c => c.DetailedErrors = true) .AddHubOptions(h => h.EnableDetailedErrors=true); if (!UserAzureSignalR) { services.AddSignalR(options => { options.EnableDetailedErrors = true; }); } else { services.AddSignalR(options => { options.EnableDetailedErrors = true; }) .AddAzureSignalR(options => { options.ConnectionString = AppConfig.SignalRConnectionString; options.ServerStickyMode = Microsoft.Azure.SignalR.ServerStickyMode.Required; }); }
异常信息
Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost: Error: Unhandled exception in circuit 'ugiugh987689769889khghjghjg'.
异常堆栈
System.Collections.Generic.KeyNotFoundException: The given key 'blazorpack' was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at Microsoft.Azure.SignalR.DefaultHubMessageSerializer.SerializeMessage(String protocol, HubMessage message) at Microsoft.Azure.SignalR.ServiceLifetimeManagerBase`1.SerializeProtocol(String protocol, String method, Object[] args) at Microsoft.Azure.SignalR.ServiceLifetimeManager`1.CreateMessage(String connectionId, String methodName, Object[] args, ClientConnectionContext serviceConnectionContext) at Microsoft.Azure.SignalR.ServiceLifetimeManager`1.SendConnectionAsync(String connectionId, String methodName, Object[] args, CancellationToken cancellationToken) at Microsoft.AspNetCore.Components.Server.Circuits.RemoteRenderer.CaptureAsyncExceptions(Task task)
解决方案
- 版本兼容性检查:该问题多由Azure SignalR SDK版本与ASP.NET Core Blazor Server版本不兼容导致。确保
Microsoft.Azure.SignalRNuGet包的主版本和你的ASP.NET Core(含Blazor相关包)版本完全匹配,例如使用.NET 8时,安装对应.NET 8版本的Azure SignalR SDK。 - 手动注册BlazorPack协议:若版本匹配后问题仍存在,可在Azure SignalR配置中显式注册BlazorPack协议:
.AddAzureSignalR(options => { options.ConnectionString = AppConfig.SignalRConnectionString; options.ServerStickyMode = Microsoft.Azure.SignalR.ServerStickyMode.Required; // 注册BlazorPack协议到序列化器 options.MessageSerializer = new DefaultHubMessageSerializer(new Dictionary<string, IHubProtocol> { { "blazorpack", new Microsoft.AspNetCore.SignalR.Protocol.BlazorPackProtocol() } }); })
- 清理重建项目:旧编译缓存可能引发版本冲突,清理项目的bin和obj目录后重新编译部署。
内容的提问来源于stack exchange,提问作者ThreadRoar
相关产品推荐
相关产品推荐

