SignalR JavaScript 客户端在连接到远程 .Net Core Hub 时出错

SignalR JavaScript client error in connect to remote .Net Core Hub

我正在使用 Asp.Net Core (3) SignalR(最新版本),如此处 Microsoft 教程中所述https://docs.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-3.1,但在连接到集线器时出现错误。

服务器上安装的 NuGet 包:

Microsoft.AspNetCore.SignalR(1.1.0)
Microsoft.AspNetCore.SignalR.Core(1.1.0)

我的服务器运行在 http://localhost:52852 and the client is running at http://localhost:10843

我已将客户端 URL 添加为服务器 CORS 策略中可接受的来源。

服务器启动:

// ConfigureServices
    services.AddCors(options => 
        options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithOrigins("http://localhost:10843/")
                    .AllowCredentials();
                }));

    services.AddSignalR(hubOptions => {
        hubOptions.EnableDetailedErrors = true;
    });

// App Configure

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapHub<AsteriskHub>("/signalr");
    });

// Hub
    public class MyHub : Hub
    {
        // Some Codes ...
    }

客户 Javascript :

const connection = new signalR.HubConnectionBuilder()
    .withUrl("http://localhost:52852/signalr")
    .configureLogging(signalR.LogLevel.Information)
    .withAutomaticReconnect()
    .build();

connection.start();

我在 Microsoft 和 Asp.Net 以及 Whosebug 帖子上阅读了许多与我的问题类似的文档,但对我出现此错误的原因感到困惑:

Access to XMLHttpRequest at 'http://localhost:52852/signalr/negotiate?negotiateVersion=1' from origin 'http://localhost:10843' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

感谢您的帮助。

.WithOrigins("http://localhost:10843/")

请删除 URL 末尾的斜杠 /,如下所示。

.WithOrigins("http://localhost:10843")

此外,请使用 app.UseCors("CorsPolicy") 应用您的 CORS 策略,如下所示。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //... other middleware ...

    app.UseCors("CorsPolicy");

    app.UseRouting();

    //...

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapHub<AsteriskHub>("/signalr");
    });

    //...
}