【问题标题】:SignalR Access to fetch has been blocked by CORSSignalR 获取的访问已被 CORS 阻止
【发布时间】:2021-09-29 04:04:14
【问题描述】:

我目前关注this basic signal R tutorial。 但是因为我想在现有项目中使用它,所以我将其拆分。 Hub 位于与客户端不同的项目中。因此IP地址不同。在 Hub 的配置中,我当然启用了 cors:

    public void ConfigureServices(IServiceCollection services)
    {
                    services.AddCors();
                    services.AddControllers();
                    services.AddSignalR();
                    //other configuration code
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
            app.UseRouting();

            app.UseCors(x => x
           .AllowAnyMethod()
           .AllowAnyHeader()
           .AllowAnyOrigin()
        );

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<LiveUpdating.ChatHub>("/chatHub");
        });
    }

但是,当我现在尝试连接到客户端中的 chatHub 时(设置与上面链接中的完全相同,只是我将连接更改为 var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44316/chatHub").build(); )我收到此错误:

     Access to fetch at 'https://localhost:44316/chatHub/negotiate?negotiateVersion=1' from 
     origin 'https://localhost:44341' has been blocked by CORS policy: Response to preflight 
     request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' 
     header in the response must not be the wildcard '*' when the request's credentials mode 
     is 'include'.

当我添加 app.UseCors 时,这是否正常工作,如上所示。因为对于我所有其他的 Rest Controller,它都可以正常工作。

【问题讨论】:

  • 您是否尝试将.AllowCredentials() 添加到您的保单中?
  • 完全忘记了那个,谢谢。它有效,但我必须用 .SetIsOriginAllowed(origin => true) 替换 .AllowAnyOrigin() 才能仍然允许 anyOrigin

标签: c# asp.net cors signalr


【解决方案1】:

将 app.useCors 替换为

            app.UseCors(x => x
           .AllowAnyMethod()
           .AllowAnyHeader()
           .SetIsOriginAllowed(origin => true)
           .AllowCredentials());

修复错误

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 2019-11-01
    • 2021-07-20
    • 1970-01-01
    • 2023-01-14
    • 2019-12-18
    • 2019-12-16
    • 2019-04-28
    相关资源
    最近更新 更多