React与.NET 8后端SignalR协商请求失败,求解决方案
SignalR协商请求失败问题修复方案
问题概述
React前端(使用@microsoft/signalr 8.0.0)连接.NET 8后端SignalR Hub时,控制台报错:
SignalR fails at negotiation request: Error: Unable to connect to the server with any of the available transports
现有代码情况:
前端SignalR初始化代码
import { HubConnectionBuilder } from "@microsoft/signalr"; let signalRConn = new HubConnectionBuilder() .withUrl("https://localhost:5003/signalr/derphub", "longPolling") .configureLogging("Trace") .build(); signalRConn .start() .then(() => console.log("Connected to SignalR hub")) .catch((err) => console.error("Error connecting to hub:", err)); signalRConn.on("ReceiveMessage", (message) => { console.log("Received message:", message); });
前端代理配置
const createProxyMiddleware = require("http-proxy-middleware"); const { env } = require("process"); const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` : env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(";")[0] : "http://localhost:49594"; const context = ["/derp/**", "/signalr/**"]; module.exports = function (app) { const appProxy = createProxyMiddleware(context, { target: target, secure: false, ws: true, headers: { Connection: "Keep-Alive", }, }); app.use(appProxy); };
后端配置与Hub代码
builder.Services.AddSignalR(); // rest of project code var app = builder.Build(); app.MapHub<DerphubRHub>("/signalr/derphub");
public class DerpHub : Hub { public async Task SendMessage(string message) { await Clients.All.SendAsync("ReceiveMessage", message); } }
排查与修复步骤
修正Hub映射类名不匹配
后端MapHub<DerphubRHub>中的泛型类名与实际Hub类DerpHub不一致,会导致路由无法找到对应Hub实例,修正为:app.MapHub<DerpHub>("/signalr/derphub");调整前端连接URL与传输方式参数
前端硬写后端端口会绕过代理引发跨域问题,且传输方式参数格式错误,修正为相对路径并使用正确参数格式:import { HubConnectionBuilder, HttpTransportType } from "@microsoft/signalr"; let signalRConn = new HubConnectionBuilder() .withUrl("/signalr/derphub", { transport: HttpTransportType.LongPolling }) .configureLogging("Trace") .build();验证代理目标端口正确性
确认ASPNETCORE_HTTPS_PORT环境变量值为后端实际运行的HTTPS端口(如5003),或直接将target硬写为"https://localhost:5003"测试,避免代理指向错误地址。检查后端中间件顺序
确保app.MapHub的调用顺序在app.UseRouting()和app.UseAuthorization()之后(若启用授权),中间件顺序错误会导致Hub路由无法被正确解析:var app = builder.Build(); // 其他中间件... app.UseRouting(); app.UseAuthorization(); app.MapHub<DerpHub>("/signalr/derphub"); // 其他端点映射...开启后端详细日志排查
在appsettings.json中添加SignalR日志配置,获取更详细的连接错误信息:{ "Logging": { "LogLevel": { "Microsoft.AspNetCore.SignalR": "Debug", "Microsoft.AspNetCore.Http.Connections": "Debug" } } }
验证修复
完成上述修改后,重启前后端服务:
- 前端控制台应输出
Connected to SignalR hub - 调用后端
SendMessage方法,前端应能收到ReceiveMessage事件并打印消息
内容的提问来源于stack exchange,提问作者martijn
相关产品推荐
相关产品推荐

