Failing to connect to a SignalR hub from Javascrip

2019-08-11 08:51发布

问题:

I'm trying to connect to a SignalR hub that is located in a seperate Web Api project from a MVC project but the connection keeps failing with error. I'm testing locally but apparently if you use IE it will handle Cross domain for you.

In 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)

In IE

Connection Error: Error during negotiation request.

Here is the server code for the hub.

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

Here is the Javascript attempting to connect to the hub. This is located in a separate MVC app.

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

Is there something I'm missing in the connection process?

回答1:

Try by modifying your code to below

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