【问题标题】:SignalR send message from client to server errorSignalR 将消息从客户端发送到服务器错误
【发布时间】:2019-11-11 11:22:18
【问题描述】:

我正在尝试将消息从 c# 控制台应用程序发送到我的 ASP.NET Core Hub。

服务器正在运行,但是当我尝试向集线器发送消息时,我得到以下预期:

抛出异常:Microsoft.AspNet.SignalR.Client.dll 中的“System.InvalidOperationException” Microsoft.AspNet.SignalR.Client.dll 中出现“System.InvalidOperationException”类型的未处理异常 连接尚未建立。

我不知道为什么客户端没有连接。 我也尝试像这样开始连接:

connection.Start().Wait();

但是打印“客户端已连接”将永远不会被执行!

服务器

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();

            // register middleware for SignalR
            app.UseSignalR(routes =>
            {
                // the url most start with lower letter
                routes.MapHub<TestHub>("/hub");
            });

        }

中心类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.AspNetCore.SignalR;

namespace CoreSignalRServer.Hubs
{
    public class TestHub : Hub
    {
        public void HelloMethod(String line)
        {
            System.Diagnostics.Debug.Write(line);
        }
}
}

客户

        static void Main(string[] args)
        {

            Console.WriteLine("Client started!");

            HubConnection connection = new HubConnection("http://localhost:44384/hub");
            IHubProxy _hub = connection.CreateHubProxy("TestHub");
            connection.Start();

            Console.WriteLine("Client connected!");

            string line = null;
            while ((line = System.Console.ReadLine()) != null)
            {
                _hub.Invoke("HelloMethod", line).Wait();
            }
}

【问题讨论】:

  • 您确定 CORS 没有干扰吗?是只听http还是https? ...
  • 我不知道如何检查 CORS。我尝试了 http 和 https,结果相同
  • 是 Core 3.0 还是更早的版本?
  • 这是 ASP.NET Core 2.1
  • 我随意更改了标签,因为答案可能取决于版本。

标签: c# asp.net-core signalr asp.net-core-2.1


【解决方案1】:

我正在尝试将消息从 c# 控制台应用程序发送到我的 ASP.NET Core Hub。

据我所知,ASP.NET Core SignalR 与 ASP.NET SignalR 的客户端或服务器不兼容。如果您想连接到 Hub 服务器(基于 ASP.NET Core SignalR)并从控制台应用程序(.NET Framework)发送消息,您可以将以下客户端库安装到您的应用程序:

Microsoft.AspNetCore.SignalR.Client

并通过以下代码实现。

Console.WriteLine("Client started!");


HubConnection connection = new HubConnectionBuilder()
    .WithUrl("https://localhost:44384/hub/TestHub")
    .Build();

connection.StartAsync().Wait();

Console.WriteLine("Client connected!");

string line = null;
while ((line = System.Console.ReadLine()) != null)
{
    connection.InvokeAsync("HelloMethod", line);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多