ASP.net核心信号器角度客户端,错误“对预检请求的响应未通过访问控制检查”

时间:2018-10-03 14:59:09

标签: c# angular asp.net-core signalr

所以我在ConfigureServices方法的ASP.Net核心服务器startup.cs中有以下代码:

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

在Configure方法中:

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,要么以某种方式更改服务器端代码,以发送将Access-Control-Allow-Credentials响应标头设置为true。 问题是我不知道该怎么做,在任何地方都找不到withCredentials的设置。

1 个答案:

答案 0 :(得分:1)

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