【问题标题】:SignalR client doesn't connect to server with http protocolSignalR 客户端未使用 http 协议连接到服务器
【发布时间】:2020-07-09 13:55:36
【问题描述】:

我已经使用 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);
    });

【问题讨论】:

  • 您收到的错误信息是什么? “正常”http请求是否有效?也许你没有打开 http 端口或使用 https 端口并尝试通过 http 连接到它?
  • 我没有收到任何错误,但连接没有打开。 http 一切正常,我不是在 prod 中启动我的后端应用程序,而是在 Visual Studio 的开发模式下启动

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


【解决方案1】:

好吧,我解决了这个问题,将选项对象添加到 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 字符串后添加选项对象,它变得有效。 关于这个对象。首先 signalR 进行协商(就像前后之间的一些握手),如果传输类型只是 websockets - 你应该跳过它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2013-12-22
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多