I've recently had to create a demo for a SignalR project I'm working on. SignalR is awesome when it comes to enabling real-time communications for your application. The amazing thing about SignalR, apart from how easy it is to use, is that it works across many different application types and platforms. You can use it on website, desktop apps and even mobile apps (both native and Xamarin). If you want to know more, have a look at the [official website](http://www.asp.net/signalr/overview" target="_blank)
However, as with everything else, sometimes things don't work as you would expect them. SignalR is incredibly easy to setup when working under the same domain. No CORS to worry about. Nonetheless, as in my example, you may want to run the SignalR server on a different domain for many reasons like scalability, availability, isolation etc. The official documentation does a good job in explaining the server side requirements for enabling CORS but the client side proxy setup wasn't as clear as I would have liked it to be.
In this post, I'll explain, as succinctly as possible, how to enable CORS between a client and server with SignalR (current version is 2.2). I will assume that your server hub and client-side code are already in place in order to focus on the configuration side of things.
Firstly, you need to install the following NuGet package : Microsoft.Owin.Cors
Next, you need to change the
Startup.cs file as per the example below:
This will instruct Owin, our middleware, to intercept all calls with
signalr in the URL and process them accordingly. This is all we need to do on the server. No
web.config changes or anything else. Just a few lines of code.
The changes on the client side are a bit more involved as we need to indicate where the SignalR Hub is and where we can get the generated proxy. This is what we need to do:
- Change the location of the SignalR generated proxy file
- Indicate the connection URL
Looking at the working example above, the lines that are important are 3 and 7. Line 3 points to the auto-generated proxy and line 7 defines the connection settings for our hub. Notice how they both match. Obviously you'll need to replace the IP Address + Port number with your domain name to make it work. If the script reference on line 3 is wrong, you'll get the following error message:
If the IP Address on line 7 is wrong, then you'll get the following error message:
The error clearly indicates that our request to connect to the SignalR hub was correct, but was blocked due to CORS misconfiguration or wrong IP address. As long as you assigne the correct SignalR hub URL your code should work. Please note that you'll need to include
/signalr in the URL otherwise the Owin CORS configuration will fail.
I hope this saves you a few headaches and makes it more clear what needs to be done to enable CORS for your SignalR implementation