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

thelittlewozniak picture thelittlewozniak · Feb 22, 2019 · Viewed 7.9k times · Source

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'));

Answer

BRAHIM Kamel picture BRAHIM Kamel · Feb 29, 2020

Note this can be applied to .net core 3.1

As it's stated on microsoft docs it seems doesn't work docs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Preceding code ommitted.
    app.UseRouting();

    app.UseCors();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

    // Following code ommited.
}

Warning

With endpoint routing, the CORS middleware must be configured to execute between the calls to UseRouting and UseEndpoints. Incorrect configuration will cause the middleware to stop functioning correctly.

But if you move your UseCors() in the first place your application will work as expected so the working code will be

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
                options.AddDefaultPolicy(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//place your useCors here 
    app.UseCors();
    app.UseRouting();


    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

    // Following code ommited.
}