Reputation: 17078
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
Upvotes: 7
Views: 9381
Reputation: 1
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.WithOrigins("http://localhost:4200");
}));
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<BroadcastHub>("/notify");
});
}
ngOnInit(): void {
const connection = new signalR.HubConnectionBuilder()
.configureLogging(signalR.LogLevel.Information)
.withUrl(environment.baseUrl + 'notify')
.build();
connection.start().then( () => {
console.log('SignalR Connected!');
}).catch( (err) => {
return console.error(err.toString());
});
// BoradcastMessage is the name of the function in your SignalR
// interface.
connection.on('BroadcastMessage', () => {
console.log('Message from server');
});
}
Upvotes: 0
Reputation: 9815
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();
}
Upvotes: 15