0
votes

I'm using Asp.Net Core (3) SignalR (Latest Version) as described in Microsoft's tutorial at here https://docs.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-3.1 but having error in connect to hub.

NuGet packages installed on server:

Microsoft.AspNetCore.SignalR(1.1.0)
Microsoft.AspNetCore.SignalR.Core(1.1.0)

My server runs at http://localhost:52852 and the client is running at http://localhost:10843.

I have added the client URL as acceptable Origin in server CORS policy.

Server Startup :

// ConfigureServices
    services.AddCors(options => 
        options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithOrigins("http://localhost:10843/")
                    .AllowCredentials();
                }));

    services.AddSignalR(hubOptions => {
        hubOptions.EnableDetailedErrors = true;
    });

// App Configure

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapHub<AsteriskHub>("/signalr");
    });

// Hub
    public class MyHub : Hub
    {
        // Some Codes ...
    }

Client Javascript :

const connection = new signalR.HubConnectionBuilder()
    .withUrl("http://localhost:52852/signalr")
    .configureLogging(signalR.LogLevel.Information)
    .withAutomaticReconnect()
    .build();

connection.start();

I have read many documents similar to my issue over Microsoft and Asp.Net and Stackoverflow posts but confused why I have this error:

Access to XMLHttpRequest at 'http://localhost:52852/signalr/negotiate?negotiateVersion=1' from origin 'http://localhost:10843' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Thanks for any help.

1

1 Answers

1
votes

.WithOrigins("http://localhost:10843/")

Please remove trailing slash / from the end of your URL, like below.

.WithOrigins("http://localhost:10843")

Besides, please apply your CORS policy with app.UseCors("CorsPolicy"), like below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //... other middleware ...

    app.UseCors("CorsPolicy");

    app.UseRouting();

    //...

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapHub<AsteriskHub>("/signalr");
    });

    //...
}