我的项目中有这个 SignalR 连接,除非 url 从 root 更改,否则它工作正常。 例如:
localhost:5001/notifications
工作正常,但是当导航期间更改 url 时,假设 https://localhost:5001/Identity/Account/Manage
signalR 连接失败,并且在浏览器控制台中,它将映射到新 url 的 SignalR 连接 url 显示为 https://localhost:5001/Identity/Account/Manage/notificationHub/negotiate?negotiateVersion=1
中心类
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 () {
//do something
})
.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.
为了避免这种行为,您可以尝试以下代码:
var connection = new signalR.HubConnectionBuilder()
.withUrl('/notificationHub', {
// Ensure the client always connects to the root, not relative to the current path
transport: signalR.HttpTransportType.WebSockets
})
.build();
connection.on('ReceiveNotification', function (result, count) {
console.log('Result', result);
});
connection
.start()
.then(function () {
// Do something
})
.catch(function (err) {
console.error(err.toString());
});