Search code examples
c#asp.net-coresignalrasp.net-core-2.2

Cannot connect SignalR client running on a port to a .NET Core 2.2 server


I have a .NET Core 2.2 server running locally on http://localhost:5002 and a client (mostly copy/pasted from Microsoft's docs) running on http://localhost:5000.

On the server side I have the sample hub from the docs, just renamed to TestHub, and the following bits in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddSignalR(options => { options.EnableDetailedErrors = true; });
    services.AddCors();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

public void Configure(IApplicationBuilder app)
{
    ...

    app.UsePathBase("/custom");
    app.UseSignalR(routes => 
    {
        routes.MapHub<TestHub>("/test");
    });
    app.UseCors(options => options
        .AllowAnyHeader()
        .AllowAnyMethod()
        .WithOrigins("http://localhost:5000")
        .AllowCredentials());
    app.UseMvc();
}

The CORS config was adapted from this GitHub issue.

On the client side I installed the @microsoft/signalr package using the instructions from the docs, then slightly changed the chat.js file to use the server's url.

"use strict";

// This is the only line I changed
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:5002/test").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    ...
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    ...
});

I tried both http://localhost:5002/test and http://localhost:5002/custom/test, but nothing works. Chrome just says net::ERR_FAILED, while Firefox reports a 405 response for an OPTIONS call to http://localhost:5002/test/negotiate?negotiateVersion=1. Both browsers, however, warn that not Access-Control-Allow-Origin header is present, which is odd since I was expecting the CORS config to take care of it.


Solution

  • In the end I set the CORS config before all other middleware in the pipeline (such as AddSignalR) and it finally worked.

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors(...);
    
        // Everything else
    }