我正在尝试连接到位于 MVC 项目之外的单独 Web Api 项目中的 SignalR 集线器,但连接始终失败并出现错误。我正在本地测试,但显然如果你使用 IE,它会为你处理跨域。
在 Chrome 中
http://localhost:53453/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22gweventhub%22%7D%5D&_=1430342757730 Failed to load resource: the server responded with a status of 404 (Not Found)
在 IE 中
Connection Error: Error during negotiation request.
这是集线器的服务器代码。
[HubName("GWEventHub")]
public class GatewayEventHub : Hub
{
public override Task OnConnected()
{
this.Groups.Add(this.Context.ConnectionId, this.Context.Request.User.Identity.Name);
return (base.OnConnected());
}
public override Task OnDisconnected(bool stopCalled)
{
this.Groups.Remove(this.Context.ConnectionId, this.Context.Request.User.Identity.Name);
return base.OnDisconnected(stopCalled);
}
}
这是尝试连接到集线器的 Javascript。它位于单独的 MVC 应用程序中。
$(function () {
var connection = $.hubConnection('http://localhost:53453');
connection.logging = true;
var hub = connection.createHubProxy('GWEventHub');
hub.logging = true;
function handleMessage(message) {
console.log('message from hub: ' + message);
}
hub.on('sendUserMessage', handleMessage);
connection.start()
.done(function() {
alert('connect to GatewayEventHub, Connection ID = ' + connection.id);
})
.fail(function(e) {
console.log('Connection Error ' + e);
});
});
我在连接过程中遗漏了什么吗?
最佳答案
尝试将代码修改为以下内容
$.connection.hub.url = "http://localhost:53453/signalr";
var hub = $.connection.GWEventHub;
//rest of your logging and other functions goes here
$.connection.hub.start().done(function() {
alert('connect to GatewayEventHub, Connection ID = ' + $.connection.hub.id);
})
.fail(function(e) {
console.log('Connection Error ' + e);
});
关于javascript - 无法从 Javascript 连接到 SignalR 集线器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29954672/