ASP.net 核心信号器角度客户端,错误"Response to preflight request doesn't pass access control check"



所以我在核心服务器启动 ASP.Net.cs在配置服务方法中有这段代码:

services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("https://localhost:44345");
}));

并在配置方法中:

app.UseCors("CorsPolicy");

在角度我有这个:

ngOnInit(): void

{

this._hubConnection = new signalR.HubConnectionBuilder().withUrl('https://localhost:44305/hub').build();
this._hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :('));

}

客户端部分和服务器部分将在不同的域上运行,它们是Visual Studio中的2个独立项目。

无论如何,在运行角度代码时,我收到此错误:

Failed to load https://localhost:44305/hub/negotiate: 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'. Origin 'https://localhost:44345' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

所以我想我有 2 个选项,要么让客户端代码为 withCredentials 属性传递 false,要么以某种方式更改服务器端代码,让它发送设置为 true 的访问控制允许凭据响应标头。 问题是我不知道如何做这两件事,我在任何地方都找不到 withCredentials 的设置。

我已经解决了,我需要包括.AllowCredentials(( 在 services.addCors 部分中。

最新更新