德州做网站公司电话,投资项目,seo入门到精通,如何添加网站 icoSignalR for ASP.Net Core 是 SignalR 的浴火重生版#xff0c;允许你在 ASP.Net Core 中实现实时通讯#xff0c;这里的 实时 意味着双方都能快速的感知对方发来的消息#xff0c;比如#xff1a;一旦 server 端有需要推送的内容将会直接 push 到 client#xff0c;这和原… 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: {controllerHome}/{actionIndex}/{id?});endpoints.MapHubMessageHub(/messagehub);});}创建 SignalR client SignalR 的 client 是任意的意味着它可以是 html, windowform, wpfconsole 甚至是 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.Onstring, 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 端如下图所示serverclient译文链接https://www.infoworld.com/article/3267165/how-to-use-signalr-in-aspnet-core.html