使用.Net Core版本的SingalR服务器构建与使用.NET Framework的客户端构建进行对话

问题描述

我已经设置了.NET Core SignalR服务器。它使用Microsoft.AspNetCore.SignalRMicrosoft.AspNetCore.SignalR.Core nuget包。在启动类中按如下方式配置此应用程序。

public class Startup
{
    public IConfiguration Configuration;

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chatHub");
        });
    }
}

ChatHub类公开了一个SendThisMessage方法,如下所示。

public class ChatHub : Hub
{

    public ChatHub() { }

    // Overrides
    public override Task OnConnectedAsync()
    {
        Console.WriteLine($"OnConnectedAsync - {this.Context.ConnectionId}");
        return base.OnConnectedAsync();
    }

    public override Task OndisconnectedAsync(Exception exp)
    {
        Console.WriteLine($"OndisconnectedAsync - {this.Context.ConnectionId}");
        return base.OndisconnectedAsync(exp);
    }

    public async Task SendThisMessage(string userName,string message)
    {
        Console.WriteLine("Hello SendThisMessage");
        await Clients.All.SendAsync("ReceiveMessage",userName,message);
    }
}

我创建了一个简单的.NET Core客户端,如下所示,并且按预期工作。请注意,它使用Microsoft.AspNetCore.SignalR.Client nuget包

static void Main(string[] args)
{
    var connection = new HubConnectionBuilder()
        .WithUrl("http://localhost:5000/chatHub")
        .Build();


    connection.StartAsync().Wait();
    connection.InvokeCoreAsync("SendThisMessage",args: new[] { "hello","world" });
    connection.On("ReceiveMessage",(string userName,string message) =>
    {
        Console.WriteLine(userName + " ; " + message);
    });
    Console.ReadKey();
} 

但是,我还需要为.NET Framework 4.6构建类似的客户端。这使用Microsoft.AspNet.SignalR.Client nuget包。为此,我从以下代码开始。

static void Main(string[] args)
{
    HubConnection connection = new HubConnection("http://localhost:5000/");
    IHubProxy proxy = connection.CreateHubProxy("chatHub");

    connection.Start().Wait();
    Console.ReadKey();

}

它会导致以下异常。

内部异常1:HttpClientException:StatusCode:404,ReasonPhrase: '未找到',版本:1.1,内容:System.Net.Http.StreamContent, 标头:{Cache-Control:私有日期:2020年9月2日,星期三21:43:50 GMT服务器:Microsoft-IIS / 10.0 X-Powered-通过:ASP.NET
内容长度:4935内容类型:text / html; charset = utf-8}

.NET 4.6客户端是否可以与使用.NET Core实现的SignalR服务器通信?

解决方法

简短的回答是“否”,您不能将.NET 4.x和.NET Core混合使用。 .NET Core是一个完整的重写。

关于同一件事,请参阅我的答案here,其中包含更详细的信息。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...