【问题标题】:Failing to connect to a SignalR hub from Javascript无法从 Javascript 连接到 SignalR 集线器
【发布时间】:2015-07-09 09:13:55
【问题描述】:

我正在尝试连接到位于与 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 加载资源失败:服务器响应状态为 404 (未找到)

在 IE 中

连接错误:协商请求期间出错。

这是集线器的服务器代码。

[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);
        });
});

在连接过程中我缺少什么吗?

【问题讨论】:

    标签: javascript asp.net-mvc signalr


    【解决方案1】:

    尝试将您的代码修改为以下内容

    $.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);
        });

    【讨论】:

    • 所以这似乎让我更近了一点,但现在错误是“未捕获的错误:SignalR:加载集线器时出错。确保您的集线器引用正确,例如 添加到调用信号器代码的视图中,但仍然没有运气。
    • 你能试试下面吗? 在其前面添加波浪号 (~)。
    • 不幸的是,即使在添加后我仍然遇到同样的错误:(
    • 如果我从 Visual Studio 运行调试,则会出现中断,提示“@987654321 中的第 1 行第 1 列 JavaScript 严重错误@\n\nSCRIPT1002:语法错误”
    • 您的集线器似乎无法正常生成。您是否在 BundleConfig 上捆绑了该动态集线器?如果是这样,请将其从捆绑中删除,然后重试。也可以尝试直接调用像localhost:53453/signalr/hubs 这样的服务器集线器,看看发生了什么。