簡體   English   中英

無法將在端口上運行的 SignalR 客戶端連接到 .NET Core 2.2 服務器

[英]Cannot connect SignalR client running on a port to a .NET Core 2.2 server

我有一個在http://localhost:5002上本地運行的 .NET Core 2.2 服務器和一個在http://localhost:5000上運行的客戶端(主要是從Microsoft 的文檔中復制/粘貼)。

在服務器端,我有來自文檔的示例集線器,剛剛重命名為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 配置改編自此 GitHub 問題

在客戶端,我使用文檔中的說明安裝了@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 報告405響應對http://localhost:5002/test/negotiate?negotiateVersion=1OPTIONS調用。 但是,兩個瀏覽器都警告說不存在Access-Control-Allow-Origin標頭,這很奇怪,因為我希望 CORS 配置能夠處理它。

嘗試使用 ConfigureServices 方法中的 AddCors 和 Addpolicy。 那為我解決了這個問題。

在 ConfigureServices 方法中添加:

services.AddCors(options =>
        {
            options.AddPolicy("AllowOrigin", builder =>
            builder.WithOrigins(new[] {"http://localhost:5000", "https://localhost:5000"})
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials()
            .SetIsOriginAllowed((host) => true) //for signalr cors  
            );

然后首先在 Configure 方法中添加:

app.UseCors("AllowOrigin");

最后,我在管道中的所有其他中間件(例如AddSignalR之前設置了 CORS 配置,它終於起作用了。

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

    // Everything else
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM