Search code examples
signalrsignalr-hubsignalr.client

How to send message in cross domain using signalr


In my current project I want to build messaging system but on subdomains. Suppose there is buyer.xyz.com and seller.xyz.com, the buyer and seller can send message to each other and there is no user roles, buyer and seller are from diffrent tables. when buyer send message the message gets inserted in message table and specified seller should get updated if he is currently online and vice versa. I am new in signalr. If possible please give code examples.


Solution

  • Basically, the best way to get started is the official documentation: http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#crossdomain

    You should add the Microsoft.Owin.Cors library to your project. Then in your startup class you modify the Configuration method that only had app.MapSignalR() to the following. (Note that the code is directly from the SignalR documentation - you can also specify the domain/subdomain from which it will accept connections).

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

    Then, assuming that you are interested in the JavaScript API, you specify the url to the function:

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

    Hope this helps! Good luck!