3

I have the following error in Console after migration from Asp.net core 2.2 to 3.1

Access to XMLHttpRequest at 'someuri/negotiate?negotiateVersion=1' from 
origin 'http://localhost:4208' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested 
resource.

And the following SignalR configuration:

app.UseCors(Constants.Policy);
app.UseAuthentication();

app.UseEndpoints(
          endpoints =>
          {
             endpoints.MapHub<SomeHub>("/ws/someuri");
          });

I've added the following policy:

options.AddPolicy(Constants.Policy,
                    p => 
                        p.AllowAnyHeader()
                       .AllowAnyMethod()
                       .AllowCredentials()
                       .WithOrigins("http://localhost:4208"));

But it didn't help.

Vladyslav Furdak
  • 1,765
  • 2
  • 22
  • 46

1 Answers1

0

You should configure the CORS this way and the order is important!

On your configure method:

public override void Configure(IApplicationBuilder app, HostConfiguration hostConfiguration, ILogger<Startup> logger)
{
    base.Configure(app, hostConfiguration, logger);

    app.UseWebSockets();

    app.UseCors(CorsPolicy); // first configure CORS, then map Hub

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<SomeHub>("/someuri");
    });
}

Then when adding CORS:

/// <summary>
/// Adds the CORS.
/// </summary>
private void AddCors(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(CorsPolicy, builder => builder.WithOrigins("http://localhost:4208")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials()
            .SetIsOriginAllowed((host) => true));
    });
}

You can see more detailed answer here.

Kiril1512
  • 3,231
  • 3
  • 16
  • 41