如何使用signalr跨域发送消息

How to send message in cross domain using signalr

在我当前的项目中,我想在子域上构建消息传递系统。假设有buyer.xyz.com和seller.xyz.com,买卖双方可以互相发送消息,没有用户角色,买卖双方来自不同的table。当买家发送消息时,消息会插入到消息 table 中,如果指定的卖家当前在线,则他应该得到更新,反之亦然。我是信号员的新手。如果可能请给出代码示例。

基本上,最好的入门方法是官方文档: http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#crossdomain

您应该将 Microsoft.Owin.Cors 库添加到您的项目中。然后在您的启动 class 中,将只有 app.MapSignalR()Configuration 方法修改为以下内容。 (请注意,代码直接来自 SignalR 文档 - 您还可以指定 domain/subdomain 从中接受连接)。

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

然后,假设您对 JavaScript API 感兴趣,您将 url 指定给函数:

 $.connection.hub.url = 'http://yourserver/signalr';

希望对您有所帮助!祝你好运!