Search code examples
angularasp.net-corecorssignalrangular7

CORS policy don't want to work with SignalR and ASP.NET core


I have a problem with my ASP.NET core API and my Angular Client. I want to implement SignalR to have a connection between API and Angular. The cors policy are already activated on our client and the API because we can already retrieve data from the API with our client. But the problem now is when I try to use SignalR I receive an error with CORS POLICY:

Access to XMLHttpRequest at 'http://localhost:50501/CoordinatorHub/negotiate' from origin 'http://localhost:4200' 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.

But there's already cors policy inside the Startup.cs on our API and it's like that:

In the ConfigureServices method :

services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigin",
        builder => 
        builder.WithOrigins("http://localhost:4200/")
            .AllowCredentials()
            //.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .SetIsOriginAllowedToAllowWildcardSubdomains());
});

And inside the Configure method :

app.UseCors("AllowSpecificOrigin");

In our Client we just want to try to make a connection between the API and the client and it's like that:

this.hubConnection.start({withCredentials: false}).then(() => 
     this.hubConnection.invoke('send', 'Hello'));

Solution

  • I solved my problem according to this link

    Add this block code to service

    services.AddCors(options => options.AddPolicy("CorsPolicy",
            builder =>
            {
                builder.AllowAnyHeader()
                       .AllowAnyMethod()
                       .SetIsOriginAllowed((host) => true)
                       .AllowCredentials();
            }));
    

    and add this block code in configuring app

    app.UseCors("CorsPolicy");
    app.UseSignalR(routes =>
            {
                routes.MapHub<General>("/hubs/general");
            });