Установка
bash
1dotnet add package Microsoft.AspNetCore.SignalR
Определение хаба
csharp
1public class ChatHub : Hub2{3 public async Task SendMessage(string user, string message)4 {5 await Clients.All.SendAsync("ReceiveMessage", user, message);6 }78 public async Task SendToGroup(string groupName, string message)9 {10 await Clients.Group(groupName).SendAsync("ReceiveMessage", message);11 }1213 public async Task JoinGroup(string groupName)14 {15 await Groups.AddToGroupAsync(Context.ConnectionId, groupName);16 await Clients.Group(groupName).SendAsync("UserJoined", Context.User?.Identity?.Name);17 }1819 public async Task LeaveGroup(string groupName)20 {21 await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);22 }2324 public override async Task OnConnectedAsync()25 {26 await Clients.All.SendAsync("UserConnected", Context.ConnectionId);27 await base.OnConnectedAsync();28 }2930 public override async Task OnDisconnectedAsync(Exception? exception)31 {32 await Clients.All.SendAsync("UserDisconnected", Context.ConnectionId);33 await base.OnDisconnectedAsync(exception);34 }35}
Настройка сервера
csharp
1// Program.cs2builder.Services.AddSignalR();34app.MapHub<ChatHub>("/chathub");
Клиент на JavaScript
javascript
1import * as signalR from "@microsoft/signalr";23const connection = new signalR.HubConnectionBuilder()4 .withUrl("/chathub")5 .configureLogging(signalR.LogLevel.Information)6 .build();78connection.on("ReceiveMessage", (user, message) => {9 console.log(`${user}: ${message}`);10});1112connection.start().catch(err => console.error(err));1314// Отправка сообщения15await connection.invoke("SendMessage", "User", "Hello!");
Клиент на C# (WPF/MAUI)
csharp
1var connection = new HubConnectionBuilder()2 .WithUrl("https://localhost:5001/chathub")3 .Build();45connection.On<string, string>("ReceiveMessage", (user, message) =>6{7 Console.WriteLine($"{user}: {message}");8});910await connection.StartAsync();11await connection.InvokeAsync("SendMessage", "User", "Hello!");
Группы
csharp
1// Добавление в группу2await Groups.AddToGroupAsync(Context.ConnectionId, "developers");34// Отправка в группу5await Clients.Group("developers").SendAsync("Notify", "New deploy!");67// Удаление из группы8await Groups.RemoveFromGroupAsync(Context.ConnectionId, "developers");
Авторизация
csharp
1[Authorize]2public class SecureHub : Hub3{4 public async Task SendPrivateMessage(string userId, string message)5 {6 await Clients.User(userId).SendAsync("ReceivePrivate", message);7 }8}910// Настройка авторизации11builder.Services.AddSignalR()12 .AddHubOptions<SecureHub>(options =>13 {14 options.ClientTimeoutInterval = TimeSpan.FromSeconds(30);15 options.KeepAliveInterval = TimeSpan.FromSeconds(15);16 });
Масштабирование
▸Redis-бэкенд
csharp
1builder.Services.AddSignalR()2 .AddStackExchangeRedis("localhost:6379", options =>3 {4 options.Configuration.ChannelPrefix = "MyApp";5 });
▸Azure SignalR Service
csharp
1builder.Services.AddSignalR()2 .AddAzureSignalR(builder.Configuration["AzureSignalR:ConnectionString"]);
Заключение
SignalR — это мощный инструмент для создания real-time приложений в .NET. Хабы, группы и authorизация предоставляет полный набор функций для чатов, уведомлений и других сценариев.