SignalR跨域javascript客户端集线器启动方法仅在订阅客户端方法时失败

时间:2016-03-10 11:28:57

标签: javascript signalr

SignalR跨域javascript客户端集线器启动方法仅在订阅客户端方法时失败。如果未订阅客户端方法,则成功调用集线器启动,并成功调用服务器方法

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

如果未订阅chatHub.client.displayMessage。它开始并连接良好。

但是如果订阅了客户端方法,则它不会连接并抛出

否接入控制允许来源集管是存在的 - 上的请求的资源 有点错误。

失败:订阅客户端方法时 **Failure: While subscribing Client Methods**

未订阅客户端方法时成功 Success while NOT subscribing Client Methods

更新

忘了提到我正在使用 CORS for SignalR ,正如Jay在下面指出的那样。它是一个带有WebAPI控制器的 MVC应用程序

请帮忙!

2 个答案:

答案 0 :(得分:2)

响应状态500(内部服务器错误)是关于集线器的OnConnected方法中的空引用。能够使用提琴手来解决这个问题。

答案 1 :(得分:1)

在前端,确保您设置cors支持

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

在服务器上,在启动类中,通过添加:

确保允许使用cors
  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);
        });

有关Cors / JSONP支持的信息,请访问:asp net

相关问题