.NET Core SignalR客户端未连接到ASP.NET Core集线器

时间:2019-05-20 18:27:34

标签: asp.net-core signalr

我有一个带SignalR集线器的ASP.NET Core Web API和一个充当集线器客户端的.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
}

我尝试了各种路线和枢纽的重命名,但是仍然无法正常工作。还尝试了此处显示的解决方案,因为它是一个类似的问题,但仍然没有结果:HttpClientException when connecting to working hub from SignalR .NET Client

服务器: DI注册:

            services.AddSignalR();

中间件注册:

            ...

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

补习班:

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

1 个答案:

答案 0 :(得分:2)

  

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