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

SignalR连接在非根路径URL下失效的技术问题咨询

SignalR非根路径页面连接失败问题解决

问题情况

SignalR连接在根路径URL下正常工作,但导航至非根路径URL时连接失败:

  • 访问localhost:5001/notifications时连接正常
  • 访问https://localhost:5001/Identity/Account/Manage时,SignalR连接返回404错误,浏览器控制台显示连接URL被错误映射为https://localhost:5001/Identity/Account/Manage/notificationHub/negotiate?negotiateVersion=1

相关代码

Hub类

public class NotificationHub : Hub { }

前端连接代码(notification.js)

var connection = new signalR.HubConnectionBuilder()
  .withUrl('/notificationHub')
  .build()

connection.on('ReceiveNotification', function (result, count) {
  console.log('Result', result)
})

connection
  .start()
  .then(function () {
    // 业务逻辑
  })
  .catch(function (err) {
    console.error(err.toString())
  })

后端路由配置(Startup.cs)

app.UseEndpoints(ep =>{
    ep.MapHub<NotificationHub>("/notificationHub");
});

浏览器控制台错误日志

Normalizing 'notificationHub' to 'https://localhost:5001/Identity/Account/notificationHub'
signalr.js:447 [2024-01-29T13:55:39.520Z] Error: Failed to start the connection: Error: Failed to complete negotiation with the server: Error: : Status code '404' Either this is not a SignalR endpoint or there is a proxy blocking the connection.
log @ signalr.js:447
notification.js:66 Error: Failed to complete negotiation with the server: Error: : Status code '404' Either this is not a SignalR endpoint or there is a proxy blocking the connection.

问题原因及解决方法

核心原因

当SignalR连接URL使用**相对路径(不带开头斜杠)**时,浏览器会基于当前页面的URL拼接路径,导致在非根路径页面中,连接URL被错误地指向当前子路径下的Hub端点,而服务器的Hub实际部署在根路径/notificationHub,因此返回404。从控制台日志可见,实际运行时传递给withUrl的是无开头斜杠的notificationHub,这是最常见的疏漏点。

解决步骤

  1. 使用绝对根路径连接:在路径前添加斜杠,强制浏览器从网站根目录开始解析:
var connection = new signalR.HubConnectionBuilder()
  .withUrl('/notificationHub') // 开头的斜杠是关键
  .build()
  1. 应用部署在子路径下的处理:

    • 方式一:通过页面<base>标签获取根路径拼接
    var baseUrl = document.querySelector('base').href;
    var connection = new signalR.HubConnectionBuilder()
      .withUrl(baseUrl + 'notificationHub')
      .build()
    
    • 方式二:手动指定完整绝对URL
    var connection = new signalR.HubConnectionBuilder()
      .withUrl('https://localhost:5001/notificationHub')
      .build()
    
  2. 验证代码一致性:检查notification.js的实际运行代码,确认确实使用了带开头斜杠的路径,避免编译、打包过程中路径被意外修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 08:14:54