i在Stackoverflow和Microsoft官方文档上的许多帖子中尝试了许多不同的解决方案(帖子可能有点旧,因为它们使用了.NET 7和Angular 2.2)。
MyFrontend signalr client具有以下代码可以连接到后端:
private startConnection() { this.hubConnection = new HubConnectionBuilder() .withUrl('http://localhost:7002/hubs/communication') .withAutomaticReconnect([100, 200, 500, 1000, 2000, 3000, 5000]) .build(); this.hubConnection .start() .then(() => console.log('Connection to Communication Hub succesful!')) .catch(err => console.log('Error establishing connection to Communication Hub: ' + err)); }
在我的后端,我现在有的代码如下:
program.cs
:在Jasonpan建议更改订单之后,我现在就这样拥有这样的顺序:
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", policy => policy.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
});
var webSocketOptions = new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromMinutes(2)
};
webSocketOptions.AllowedOrigins.Add("http://localhost:4200");
// Code omitted for brevity
app.MapHub<CommunicationHub>("/hubs/communication");
app.UseCors("CorsPolicy");
app.UseWebSockets(webSocketOptions);
我做错了什么?任何帮助都将不胜感激:)。
update2:这是一个小型示例项目:https://gitlab.com/arendevel/corsissue
thanks to @brennan和@jasonpan我可以发现问题是从前端连接到后端的HTTP端口,并具有HTTPS重定向。直接连接到HTTPS端口为我解决了。