问题描述
我已经设置了.NET Core SignalR服务器。它使用Microsoft.AspNetCore.SignalR
和Microsoft.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,其中包含更详细的信息。