SignalR cross-domain javascript client hub start m

2019-07-14 19:01发布

SignalR cross-domain javascript client hub start method fails only when client methods are subscribed. If client methods are not subscribed, hub start is successfully called and the server methods are called successfully.

$.connection.hub.url = 'http://my-cross-domain.com:876/signalr';
$.connection.hub.logging = true;
var chatHub = $.connection.chatHub;

chatHub.client.displayMessage = function (windowID, message) {
    alert("test");
};

$.connection.hub.start().done(function () {
    alert("Connected");
});

If chatHub.client.displayMessage is not subscribed. It starts and connects well.

But if the client method is subscribed, it doesn't connect and throws the

no-access-control-allow-origin-header-is-present-on-the-requested-resource kind of error.

Failure: While subscribing Client Methods **Failure: While subscribing Client Methods**

Success while NOT subscribing Client Methods Success while NOT subscribing Client Methods

UPDATE:

Forgot to mention that I am using CORS for SignalR exactly as Jay pointed out below. Its an MVC Application with a WebAPI controller as well.

Please help!

2条回答
▲ chillily
2楼-- · 2019-07-14 19:38

Response status 500 (Internal Server Error) is about a null reference in the OnConnected method of the Hub. Was able to figure that out using the Fiddler.

查看更多
趁早两清
3楼-- · 2019-07-14 19:49

On the front end make sure you are NOT setting cors support

jQuery.support.cors = true //Do not put this

On the server, in your startup class, make sure cors is allowed by adding:

  app.Map("/signalr", map =>
        {
            // Setup the CORS middleware to run before SignalR.
            // By default this will allow all origins. You can 
            // configure the set of origins and/or http verbs by
            // providing a cors options with a different policy.
            map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration 
            {
                // You can enable JSONP by uncommenting line below.
                // JSONP requests are insecure but some older browsers (and some
                // versions of IE) require JSONP to work cross domain
                // EnableJSONP = true
            };
            // Run the SignalR pipeline. We're not using MapSignalR
            // since this branch already runs under the "/signalr"
            // path.
            map.RunSignalR(hubConfiguration);
        });

Info on Cors/JSONP support can be found at: asp net

查看更多
登录 后发表回答