是否可以使用 SignalR ASP.NET 服务器和 SignalR WinForms 应用程序客户端?

Is it possible to use a SignalR ASP.NET Server and SignalR WinForms App Client?

我想使用 SignalR 在 3 个简单的 Windows Forms 应用程序和 ASP.NET Web API 服务器之间创建通信。 我根据位于 https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-5.0&tabs=visual-studio 的 Microsoft 文档设置了服务器。我什至学习了 PluralSight 课程 'Getting Started With ASP.NET Core SignalR',但这似乎有点过时了。

[HubName("MyNetworkHub")]
    public class NetworkHub : Hub
    {
        private readonly ISomeService_someService;
        public NetworkHub(ISomeService someService)
        {
            _someService = someService;
        }

        public Task SendMessage(string message)
        {
            return Clients.All.SendAsync("ReceiveMessage", message);
        }
    }

Startup.cs 我添加了配置:

public void ConfigureServices(IServiceCollection services)
  {
    ...
    services.AddSignalR();
    ...
  }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
    ...
    app.UseEndpoints(endpoints =>
      {
         endpoints.MapControllers();
         endpoints.MapHub<NetworkHub>("/networkhub");
      });
  }

对于我的客户,我想使用 Windows Forms Applications,因为我要在复杂的技术上构建一个简单的原型。我创建了 1 个控制台应用程序来尝试连接,如下所示:

using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Threading.Tasks;
...
    class Program
    {
        static async Task Main(string[] args)
        {
            HubConnection connection = null;
            try
            {
                connection = new HubConnectionBuilder()
                    .WithUrl("http://127.0.0.1:52366/MyNetworkHub")
                    .Build();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
            // The part below might be wrong, but I can't fix that if the connection doesn't work.
   
            connection.On<string>("ReceiveMessage", (message) =>
            {
                Console.WriteLine(message);
            });

            await connection.StartAsync();
        }
    }

我见过几个尝试同样事情的人的例子,但他们都 运行 遇到了连接问题。我 运行 遇到的问题是我无法启动连接,因为我得到:

Could not load file or assembly 'System.Text.Encodings.Web, Version=5.0.0.0, Culture=neutral, PublicKeyToken=xxxx'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)

我尝试将 .WithUrl("http://127.0.0.1:52366/MyNetworkHub") 换成 .WithUrl("http://127.0.0.1:52366/networkhub"),但这导致了同样的错误。

我已经通过将 System.Text.Encodings.Web 包添加到客户端的 .csproj 中解决了这个问题。

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="5.0.0" />
    <PackageReference Include="System.Text.Encodings.Web" Version="5.0.0" />
  </ItemGroup>