Home > Blockchain >  SignalR ping fails with CORS Access-Control-Allow-Origin error
SignalR ping fails with CORS Access-Control-Allow-Origin error

Time:02-01

In my project, the negotiate, connect and start API calls all contain the required access-control-allow-origin header. However, as soon as SignalR calls the ping method, it throws the following error:

Access to XMLHttpRequest at 'https://backend.url/signalr/signalr/ping&_=1643292246714'
from origin 'https://frontend.url' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

I already modified my Startup.cs file according to Microsoft's documentation. I the old version, I was using the MapSignalR method instead.

public class Startup {
    public void Configuration(IAppBuilder app) {
        // Branch the pipeline here for requests that start with "/signalr"
        app.Map("/signalr", map =>
        {
            // Setup the CORS middleware to run before SignalR. By default this will allow all origins.
            map.UseCors(CorsOptions.AllowAll);
            map.RunSignalR();
        });

        app.UseCors(CorsOptions.AllowAll);
    }
}

However, this change didn't have any effect. The CORS error still persists. Any idea what's wrong here?

I'm using Microsoft.AspNet.SignalR 2.4.2 and Microsoft.Owin.Cors 4.2.0 with .NET Framework 4.8.

I also don't understand, why it's calling /signalr/signalr in the URL.

CodePudding user response:

Did you modify your web.config as well?

<httpProtocol>
  <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS,HEAD" />
      <add name="Access-Controls-Allow-Headers" value="content-type, accept" />
  </customHeaders>
</httpProtocol>

CodePudding user response:

You should configure your CORS like (the order is important):

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

Note: Avoid putting * in the origins, it is better to create an array of strings with the possible origins, ideally reading it from configuration.

  •  Tags:  
  • Related