.NET Core SignalR 客户端未连接到 ASP.NET Core hub

.NET Core SignalR client doesn't connect to ASP.NET Core hub

我有一个 ASP.NET Core web API,其中包含一个 SignalR Hub 和一个充当该中心客户端的 .NET Core 控制台应用程序。

控制台应用程序在尝试连接时抛出以下错误:

System.AggregateException
  HResult=0x80131500
  Message=One or more errors occurred. (StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
  Date: Mon, 20 May 2019 18:12:44 GMT
  Server: Kestrel
  Content-Length: 0
})
  Source=System.Private.CoreLib
  StackTrace:
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at SurveyApp.NotificationClient.Program.Main(String[] args) in C:\Users\user\source\repos\SurveyApp\SurveyApp.NotificationClient\Program.cs:line 16

Inner Exception 1:
HttpClientException: StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
  Date: Mon, 20 May 2019 18:12:44 GMT
  Server: Kestrel
  Content-Length: 0
}

各种路径和枢纽的重命名我都试过了,还是不行。还尝试了此处显示的解决方案,因为它是一个类似的问题,但仍然没有结果:

服务器: DI 注册:

            services.AddSignalR();

中间件注册:

            ...

            app.UseSignalR(route =>
            {
                route.MapHub<NotificationHub>("/notificationhub");
            });
            app.UseMvc();

中心 class:

public class NotificationHub : Hub
    {
        public Task SendMessage(string message)
        {
            return Clients.All.SendAsync(message);
        }

        public override Task OnConnectedAsync()
        {
            Console.WriteLine("A client connected");
            return base.OnConnectedAsync();
        }
    }

客户代码:

static void Main(string[] args)
        {
            var connection = new HubConnection("https://localhost:5001/notificationhub");
            connection
                .CreateHubProxy("NotificationHub")
                .On<string>("ReceiveNotification", Console.WriteLine);
            connection.Start().Wait();
            Console.WriteLine("Connection started");
            Console.ReadKey();
        }

当我在 connection.Start() 之后不调用 Wait() 时,我没有收到任何错误,但客户端仍然没有连接。我在服务器和客户端上都是 运行 .NET Core 2.2,SignalR nuget 的版本是 2.4.1

var connection = new HubConnection("https://localhost:5001/notificationhub");

ASP.NET Core 中不再存在此构造。似乎您正在将 ASP.NET Core SignalR 服务器与 Microsoft.AspNet.SignalR.Client 连接,这应该与 ASP.NET SignalR 兼容,但与 ASP.NET Core.

不兼容

如果是这种情况,您需要添加对 Microsoft.AspNetCore.SignalR.Client 的引用,它以 .NETStandard 2.0 为目标并且应该也能够 运行 在 .NET Framework 上。

然后创建如下连接:

var Connection = new HubConnectionBuilder()
    .WithUrl("https://localhost:5001/notificationhub")
    .ConfigureLogging(logging =>{
        logging.AddConsole();
    })
    .Build();

有关详细信息,请参阅 https://docs.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-2.2#connect-to-a-hub