我的ASP.NET核心API和Angular Client有问题。我想实现SignalR在API和Angular之间建立连接。 cors策略已在我们的客户端和API上激活,因为我们已经可以使用客户端从API检索数据。但是现在的问题是,当我尝试使用SignalR时,收到的CORS POLICY错误:
访问XMLHttpRequest在原产地为“ http://localhost:50501/CoordinatorHub/negotiate”“ http://localhost:4200”已被CORS政策阻止:对预检请求未通过访问控制检查:否请求中存在“ Access-Control-Allow-Origin”标头资源。
但是我们的API的Startup.cs内部已经有cors策略,就像这样:
在ConfigureServices方法中:
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
builder.WithOrigins("http://localhost:4200/")
.AllowCredentials()
//.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowedToAllowWildcardSubdomains());
});
并且在Configure方法中:
app.UseCors("AllowSpecificOrigin");
在我们的客户端中,我们只想尝试在API和客户端之间建立连接,就像这样:
this.hubConnection.start({withCredentials: false}).then(() =>
this.hubConnection.invoke('send', 'Hello'));
Note这可以应用于.net core 3.1
如微软文档中所述,它似乎不起作用docs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Preceding code ommitted.
app.UseRouting();
app.UseCors();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
// Following code ommited.
}
警告
使用端点路由,必须将CORS中间件配置为在对UseRouting和UseEndpoints的调用之间执行。不正确的配置将导致中间件停止正常运行。
但是如果您首先移动UseCors(),您的应用程序将按预期运行,因此工作代码将是
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
options.AddDefaultPolicy(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//place your useCors here
app.UseCors();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
// Following code ommited.
}
在启动配置类中尝试类似的操作:
app.Map("/CoordinatorHub/negotiate", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
// You can enable JSONP by uncommenting line below.
// EnableDetailedErrors = true,
// EnableJSONP = true
};
map.RunSignalR(hubConfiguration);
});