我正在使用Angle 6和asp.net核心上的SignalR功能。但是请继续获取此错误对预检请求的响应未通过访问控制检查:响应中“ Access-Control-Allow-Credentials”标头的值为“”,当请求的凭据为真时,该值必须为“ true”模式为“包含”。
进行了一些研究,发现这是服务器端的CORS问题。因此修改了服务器代码。
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");
});
}
角度应用
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);});
}
引用
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
答案 0 :(得分:5)
您必须允许您的cors策略使用凭据,因为signalr也在传递cookie。
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.WithOrigins("http://localhost:4200");
}));
services.AddSignalR();
}
答案 1 :(得分:0)
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');
});
}