从 Asp.net core 2.2 迁移到 3.1 后,控制台出现以下错误
Access to XMLHttpRequest at 'someuri/negotiate?negotiateVersion=1' from
origin 'http://localhost:4208'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource.
以及以下 SignalR
配置:
app.UseCors(Constants.Policy);
app.UseAuthentication();
app.UseEndpoints(
endpoints =>
{
endpoints.MapHub<SomeHub>("/ws/someuri");
});
我添加了以下政策:
options.AddPolicy(Constants.Policy,
p =>
p.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins("http://localhost:4208"));
但这并没有帮助。
最佳答案
您应该以这种方式配置 CORS
,顺序很重要!
在你的配置方法上:
public override void Configure(IApplicationBuilder app, HostConfiguration hostConfiguration, ILogger<Startup> logger)
{
base.Configure(app, hostConfiguration, logger);
app.UseWebSockets();
app.UseCors(CorsPolicy); // first configure CORS, then map Hub
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<SomeHub>("/someuri");
});
}
然后在添加 CORS 时:
/// <summary>
/// Adds the CORS.
/// </summary>
private void AddCors(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(CorsPolicy, builder => builder.WithOrigins("http://localhost:4208")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
}
可以看到更详细的回答here .
关于asp.net - SignalR 协商阶段发生 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60885559/