asp.net - SignalR 协商阶段发生 CORS 错误

标签 asp.net signalr asp.net-core-3.1

从 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/

相关文章:

.net 核心调用 wcf 服务 - SecurityAccessDeniedException : The security token could not be authenticated or authorized

c# - Active Directory redirect_uri 显示 IP 而不是 DNS 名称。如何在使用 Azure AD 进行身份验证时在代码中提供绝对 CallbackPath?

asp.net - 如何通过 URL 访问 Azure SQL 数据库服务器管理 UI

ASP.NET 多个联合身份提供商

asp.net - ASP.NET 中 <%# Bind ("") %> 和 <%# Eval ("") %> 有什么区别?

asp.net - 如何在 ASP.NET Core 中获取当前登录的用户 ID?

c# - 用加号解码字符串

jquery - 使用 signalR 通过 1 次广播更新多个 View

asp.net-web-api - 使用 SignalR 从长时间运行的进程推送到客户端

javascript - 类型错误 : ticker is undefined During SignalR implementation