4

I, am using the SignalR features on angular 6 and asp.net core. But keep getting this error Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

Did some research and found that it is CORS issue from the server side.So modified the server code.

startup.cs

public void ConfigureServices(IServiceCollection services)
        {
    services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader()
                           .WithOrigins("http://localhost:4200");
                }));
     services.AddSignalR();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
         app.UseCors("CorsPolicy");
         app.UseSignalR(routes =>
            {
                routes.MapHub<SignalR>("/rule");
            });
}

angular app

ngOnInit() {
this.callSignalR()
}

    private callSignalR(): void {
        // set up the signal R
        let connection = new signalR.HubConnectionBuilder().withUrl(environment.baseUrl+"/rule").build();
        //start the connection 
        connection.start().then(() => connection.invoke("updateRules", this.autheService.getCurrentuser.userId));
        //Get the response from the server
        connection.on("updateRules", data => {console.log(data);}); 
      }

references

Access-Control-Allow-Origin - Angular 5

'Access-Control-Allow-Credentials' header in the response is '' which must be 'true'

https://github.com/aspnet/SignalR/issues/2095

https://github.com/SignalR/SignalR/issues/1694

https://github.com/aspnet/SignalR/issues/2110

Camilo Terevinto
  • 26,697
  • 6
  • 67
  • 99
San Jaisy
  • 9,586
  • 15
  • 93
  • 162

1 Answers1

7

You must allow credentials for your cors-policy because signalr is passing cookies as well.

public void ConfigureServices(IServiceCollection services)
        {
    services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader()
                           .AllowCredentials()
                           .WithOrigins("http://localhost:4200");
                }));
     services.AddSignalR();
}
alsami
  • 6,371
  • 3
  • 16
  • 29
  • getting an another error as Failed to complete negotiation with the server: Error: Not Found – San Jaisy Jul 28 '18 at 09:43
  • Then your hub endpoint is not valid. that is a new error, I would suggest to create a new question for that and google before., – alsami Jul 28 '18 at 09:44
  • I've spent half the afternoon trying to figure this out and all I needed to do was add .AllowCredentials() Many thanks – Paul Oct 03 '18 at 15:52