无法将在端口上运行的SignalR客户端连接到.NET Core 2.2服务器

问题描述 投票:1回答:2

我有一个在http://localhost:5002上本地运行的.NET Core 2.2服务器,以及一个在Microsoft's docs上运行的客户端(主要是从http://localhost:5000复制/粘贴的客户端。

在服务器端,我有来自文档的示例中心,刚刚重命名为TestHub,并且在Startup.cs中包含以下位:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddSignalR(options => { options.EnableDetailedErrors = true; });
    services.AddCors();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

public void Configure(IApplicationBuilder app)
{
    ...

    app.UsePathBase("/custom");
    app.UseSignalR(routes => 
    {
        routes.MapHub<TestHub>("/test");
    });
    app.UseCors(options => options
        .AllowAnyHeader()
        .AllowAnyMethod()
        .WithOrigins("http://localhost:5000")
        .AllowCredentials());
    app.UseMvc();
}

[CORS配置改编自this GitHub issue

在客户端,我按照文档中的说明安装了@microsoft/signalr程序包,然后略微更改了chat.js文件以使用服务器的URL。

"use strict";

// This is the only line I changed
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:5002/test").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    ...
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    ...
});

我尝试了http://localhost:5002/testhttp://localhost:5002/custom/test,但没有任何效果。 Chrome仅说net::ERR_FAILED,而Firefox则报告对405OPTIONS调用为http://localhost:5002/test/negotiate?negotiateVersion=1响应。但是,两个浏览器都警告说不存在Access-Control-Allow-Origin标头,这很奇怪,因为我希望CORS配置能够处理它。

c# asp.net-core signalr asp.net-core-2.2
2个回答
1
投票

最后,我在管道(例如AddSignalR)中设置了CORS配置在所有其他中间件之前],并且终于成功了。

public void Configure(IApplicationBuilder app)
{
    app.UseCors(...);

    // Everything else
}

1
投票

尝试从您的ConfigureServices方法中尝试使用AddCors和Addpolicy。这为我解决了问题。

© www.soinside.com 2019 - 2024. All rights reserved.