如何在 ASP.Net Core 中使用 SignalR
SignalR for ASP.Net Core 是使用 SignalR 的浴火重生版,允许你在 ASP.Net Core 中实现实时通讯,使用这里的使用 实时 意味着双方都能快速的感知对方发来的消息,比如:一旦 server 端有需要推送的使用内容将会直接 push 到 client,这和原始的使用 http 单向请求有着本质的区别。
值得注意的使用是, ASP.Net Core 版的使用 SingalR 移除了老版的诸多功能,比如:
自动重连机制 消息处理机制 单连接多hub不过无需担心,网站模板使用新版的使用 SingalR 在健壮性和易用性上做了非常大的改进,总的使用来说,新版本已不兼容老版本,使用而且新的使用 SingalR 客户端采用的是 TypeScript 。
安装 SingalR
要想使用 SingalR,使用需要通过 nuget 引用 Microsoft.AspNetCore.SignalR 包,使用可以通过 Visual Studio 2019 的使用 NuGet package manager 可视化界面安装 或者 通过 NuGet package manager 命令行工具输入以下命令:
Install-Package Microsoft.AspNetCore.SignalR使用 SignalR broadcast现在我们一起实现一下如何在 ASP.Net Core 应用程序中使用 SignalR 的广播消息,那怎么做呢?创建一个自定义的 MessageHub 类并继承类库中的 Hub 基类,在 MessageHub 中定义一个 SendMessage 方法,服务器托管该方法用于向所有已连接的客户端发送消息,如下代码所示:
public class MessageHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } }配置 SignalR
要想在 ASP.Net Core 中使用 SignalR,只需在 Startup.ConfigureServices() 中调用扩展方法 AddSignalR() 将其注入到 ServiceCollection 中即可,如下代码所示:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSignalR(); services.AddControllersWithViews(); } }为了能够启用 MessageHub,需要在 Startup.Configure 方法中添加如下代码:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{ controller=Home}/{ action=Index}/{ id?}"); endpoints.MapHub<MessageHub>("/messagehub"); }); }创建 SignalR client
SignalR 的 client 是任意的,意味着它可以是 html, windowform, wpf,console 甚至是 java 程序,它们都可以消费 server 端发来的消息,接下来准备创建一个 Console 程序尝试一下,那如何做呢?需要在 client 端引用 Microsoft.AspNetCore.SignalR.Client 和 System.Text.Encodings.Web 两个nuget包,如下代码所示:
class Program { static async Task Main(string[] args) { HubConnection connection = new HubConnectionBuilder() .WithUrl("http://localhost:55215/messagehub") .Build(); connection.On<string, string>("ReceiveMessage", (user, message) => { var newMessage = $"{ user}: { message}"; Console.WriteLine(newMessage); }); await connection.StartAsync(); await connection.InvokeAsync("SendMessage", "jack", "hello,world"); Console.ReadLine(); } }接下来就可以调试一下,分别启动 server 和 client 端,亿华云如下图所示:
server
client
译文链接:https://www.infoworld.com/article/3267165/how-to-use-signalr-in-aspnet-core.html