javascript - 尝试连接到 SignalR 时出现错误 204

标签 javascript c# asp.net signalr asp.net-core-signalr

我无法在 Windows 7 下运行的 ASP.NET Core 2.0.3 应用程序中连接到我的 SignalR Hub。 我使用 NuGet 中的 SignalR 1.0.0-alpha1-final 作为服务器,使用 signalr-client-1.0.0-alpha2-final.min.js 作为 JavaScript 客户端。

这是我的中心:

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace MyProject
{
    public class MyHub: Hub
    {
        public override async Task OnConnectedAsync()
        {
            await Clients.All.InvokeAsync("Send", $"{Context.ConnectionId} joined");
        }

        public Task Send(string message)
        {
            return Clients.All.InvokeAsync("Send", $"{Context.ConnectionId}: {message}");
        }    
    }
}

在startup.cs中配置:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();
    app.UseHangfireDashboard();
    app.UseHangfireServer();

    app.UseSignalR(routes =>
    {
        routes.MapHub<MyHub>("hubs");
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });
}        

在测试页面中:

let transportType = signalR.TransportType[getParameterByName('transport')] || signalR.TransportType.WebSockets;
let http = new signalR.HttpConnection(`http://${document.location.host}/hubs`, { transport: transportType });
var connection = new signalR.HubConnection(http);

但是当执行此代码时,我从服务器收到错误 204。

更新

根据 @Gabriel Luci 的回答,这里是工作代码:

let transportType = signalR.TransportType.LongPolling;
let http = new signalR.HttpConnection(`http://${document.location.host}/hubs`, { transport: transportType });
let connection = new signalR.HubConnection(http);

connection.start();

connection.on('Send', (message) => {
    console.log(message);
});

...
connection.invoke('Echo', "Hello ");

最佳答案

GitHub 上为此提出了一个问题:https://github.com/aspnet/SignalR/issues/1028

显然 WebSockets 不适用于 IIS 和 IIS Express。您需要使用长轮询。该问题中有一段示例代码:

let connection = new HubConnection("someurl", { transport: signalR.TransportType.LongPolling });
connection.start().then(() => {});

关于javascript - 尝试连接到 SignalR 时出现错误 204,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47573121/

相关文章:

c# - 计算我的 ASP.NET MVC 项目中来自不同部门的相同产品名称的总和

c# - 如何为 FileHelpers 元素类的字段定义默认值

c# - c# asp.net 程序执行过程中遇到 fatal error

c# - 如何在图表底部放置标签

javascript - 我可以将 Base64 图像安全地存储在本地存储中吗?

javascript - 在 JavaScript/SAPUI5 中读取 Excel (xlsx) 文件数据的问题

c# - 使用 VisualBasic.DLL 的 InputBox 需要 DialogResult

c# - Azure 网站上的数据保护/加密?

javascript - 加载 &lt;script&gt; 内容后是否加载 jQuery.load() ?

javascript - 克隆没有按预期工作