SignalR客户端未通过http协议连接到服务器

时间:2020-07-09 13:55:36

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

我已经用SignalR制作了.NET Core API,当我使用https协议加载应用程序时,可以与signalR javascript客户端连接,但是当我使用http协议加载应用程序时-signalR js客户端无法连接至集线器。 CORS可以正常工作。

我的代码:Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.WithOrigins("http://localhost:3000")
                .AllowAnyMethod()
                .AllowCredentials()
                .AllowAnyHeader());
    });
    services.AddSignalR(options =>
    {
        options.EnableDetailedErrors = true;
    });
    services.AddControllers(options =>
    {
        options.EnableEndpointRouting = true;
    });
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
    logger.LogInformation($"Started Configure with is Production mode:{env.IsProduction()}");
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseCors("CorsPolicy");
    app.UseAuthorization();
    app.UseAuthentication();
    app.UseEndpoints(route =>
    {
        route.MapHub<ConnectionHub>("/chat");
        route.MapControllers();
    });
}

在我的JS应用中:

var connection = new signalR.HubConnectionBuilder()
          .withUrl("http://localhost:5066/chat") // WHEN I'M CHANGING TO HTTPS host - everything works fine
          .build();

// Create a function that the hub can call to broadcast messages.
connection.on("broadcastMessage", function (name, message) { });

connection.start()
    .then(function () {       
       connection.invoke("Send", name, messageInput.value); 
    })
    .catch((error) => {
       console.error(error.message);
    });

1 个答案:

答案 0 :(得分:0)

好吧,我解决了将选项对象添加到signalR客户端的问题(添加skipNegotiations:true)。老实说,我还不知道这是什么意思(明天我会读懂含义,然后我将对该属性进行描述)。

// Start the connection.
        var connection = new signalR.HubConnectionBuilder()
          .withUrl("http://localhost:5066/chat", {
            skipNegotiation: false,
            transport: signalR.HttpTransportType.WebSockets| 
                       signalR.HttpTransportType.LongPolling |
                       signalR.HttpTransportType.serverSentEvents,
          })
          .build();

UPD:好的,这要归功于在URL字符串后添加options对象。 关于这个对象。首先,signalR进行协商(就像前后之间的握手),如果传输类型只是websocket,则应该跳过它。