.NET 9与Angular v19中SignalR WebSocket连接错误求助
错误信息
[2025-03-14T07:24:52.776Z] Information: Normalizing '/downloadHub' to 'https://127.0.0.1:63349/downloadHub'.
Utils.js:148
[2025-03-14T07:28:52.849Z] Information: (WebSockets transport) There was an error with the transport.
chunk-J25FJFZE.js:49
[2025-03-14T07:28:52.854Z] Error: Failed to start the transport 'WebSockets': Error: WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.
排查解决思路
核对服务器端Hub注册与端点映射
检查项目的Program.cs(或Startup.cs),确认SignalR服务已注册,且/downloadHub端点正确映射到对应的Hub类:// 注册SignalR服务 builder.Services.AddSignalR(); // 映射Hub端点,确保路径和客户端一致 app.MapHub<DownloadHub>("/downloadHub");同时确认你的
DownloadHub类继承了Hub基类,没有拼写错误。确认WebSocket协议支持与环境干扰
- 本地开发时,关闭Fiddler、Charles等代理工具,避免拦截WebSocket请求。
- 若用IIS部署,需在Windows功能中启用WebSocket协议(控制面板→程序和功能→启用或关闭Windows功能→Internet信息服务→万维网服务→应用程序开发功能→WebSocket协议)。
- 跨域场景下,检查CORS配置是否允许SignalR请求:必须开启
AllowCredentials(),并允许对应前端域名的所有方法和头:builder.Services.AddCors(options => { options.AddPolicy("SignalRCors", policy => { policy.WithOrigins("https://127.0.0.1:63349") // 替换为你的前端地址 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); }); app.UseCors("SignalRCors");
检查客户端连接代码
确认客户端创建连接时的路径正确:const connection = new signalR.HubConnectionBuilder() .withUrl("/downloadHub") // 跨域场景需写完整服务器Hub地址,比如"https://your-server:port/downloadHub" .build();启动连接时捕获详细错误,方便定位:
connection.start() .catch(err => console.error("连接失败详情:", err));多服务器部署需启用粘性会话
若你的服务部署在多台服务器上,必须配置负载均衡的粘性会话(Sticky Sessions),保证同一客户端的所有请求都路由到同一服务器,否则SignalR连接会因找不到对应连接ID而失败。开启详细日志定位深层问题
服务器端添加SignalR日志过滤,查看连接过程的详细日志:builder.Logging.AddFilter("Microsoft.AspNetCore.SignalR", LogLevel.Debug); builder.Logging.AddFilter("Microsoft.AspNetCore.Http.Connections", LogLevel.Debug);客户端也可以监听连接关闭事件获取更多信息:
connection.onclose(error => { console.error("连接关闭原因:", error); });
内容的提问来源于stack exchange,提问作者D052057

