Hello!
Today something that can be quite annoying with signalR:
The need for a signalR hub from a web client, hosted on a different server from SignalR address
When we have something like this in WPF, Win8, or other .Net client; the solution is quite easy: declare 2 connections and 2 different hubs
1: _connection = new HubConnection("http://localhost:50000/");
2: _myHub = _connection.CreateHubProxy("MyHub");
3: _connection.Start().Wait();
4:
5: _connection2 = new HubConnection("http://localhost:50001/");
6: _myHub2 = _connection2.CreateHubProxy("MyHub");
7: _connection2.Start().Wait();
However in JavaScript, si not that easy
. Let’s see the following example. In this case, from a local url httl://localhost:1234, I need to use an external Hub signalR hosted at http://localhost:4316.
1: $(function () {
2: $.support.cors = true;
3: $.connection.hub.url = 'http://localhost:4316/signalr/hubs';
4: var chat = $.connection.myHub;
5: $.connection.hub.start({ jsonp: true}).done(function () {
6: console.log("connection started");
7: $('#sendmessage').click(function () {
8: chat.server.publishMessage($('#message').val());
9: });
10: });
11: });
A summary of this javascript client, can be::
- Enable JQuery CORS in javascript (line 3)
- Define the url of the connection (line 4)
- Start the connection, using jsonp (only necessary with Chrome)
However, this solution is only 50%. The next thing is to enable cross-domain calls into the server. Prior to version 2.0, there was a property of the fairly self-explanatory hub:
var config = new HubConfiguration {EnableCrossDomain = true};
Now with SignalR 2.0, also we must modify the configuration by default of Hubs, but in this case enabling JSONP.
1: public partial class Startup
2: {
3: public void Configuration(IAppBuilder app)
4: {
5: var configuration = new HubConfiguration
6: {
7: EnableJSONP = true
8: };
9: app.MapSignalR(configuration);
10: ConfigureAuth(app);
11: }
12: }
Done !!! We have cross domain enabled for calls to SignalR hubs.
Saludos @ La Finca
El Bruno
Leave a reply to Matt Cancel reply