javascript - 无法从 Javascript 连接到 SignalR 集线器

标签 javascript asp.net-mvc signalr

我正在尝试连接到位于 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/

相关文章:

javascript - 浏览器刷新后,AngularJS 设置的 Cookie 将被忽略

javascript - Webpack: 运行时出错 "npm start"

asp.net-mvc - 可以编译 Razor View 吗?

javascript - 如何在 signalR 中实现 "on"方法?

asp.net-core - 用于点对点视频聊天的 ASP.NET Core 和 WebRTC

javascript - 取决于列表项文本长度的 CSS 类

javascript - Css - 复选框上的自定义样式不起作用

c# - 将 EditorTemplate 添加到 Kendo 网格

asp.net - ASP MVC - 有问题的路线?

c# - 将 SignalR 与 ASP.NET MVC3 结合使用