- Create WebApi
- Install
Microsoft.AspNetCore.SignalR.Clientpackage - Create custom Hub class inherited from Hub
public class NotificationHub : Hub { public async Task SendMessage(string message) { await Clients.All.SendAsync("GetNotification", message); } }
- Add this line of code to Program.cs
builder.Services.AddSignalR(); ... app.MapHub<NotificationHub>("/notification");
- Create controller to send message
public class NotificationsController : ControllerBase { private readonly IHubContext<NotificationHub> _hubContext; public NotificationsController(IHubContext<NotificationHub> hubContext) { _hubContext = hubContext; } [HttpPost] public async Task<IActionResult> SendNotification(string notification) { await _hubContext.Clients.All.SendAsync("GetNotification", notification); return Ok("sent!"); } }
- Add Cors
builder.Services.AddCors(cors => { cors.AddDefaultPolicy(corsPolicy => { corsPolicy.AllowAnyHeader() .AllowAnyOrigin() .AllowAnyMethod(); }); });
- Create BlazorWasm app
- Install
Microsoft.AspNetCore.SignalR.Clientpackage - Create notification razor page
@page "/notification" @using Microsoft.AspNetCore.SignalR.Client <MudButton OnClick="@(async () => await SendNotification())">Send</MudButton> @foreach (var notification in _notifications) { <p>@notification</p><br> } @code { private readonly List<string> _notifications = new(); private HubConnection? _hubConnection; protected override async Task OnInitializedAsync() { _hubConnection = new HubConnectionBuilder() .WithUrl("<API_HOST>/notification") .Build(); _hubConnection.On<string>("GetNotification", (notification) => { _notifications.Add(notification); InvokeAsync(StateHasChanged); }); await _hubConnection.StartAsync(); } private async Task SendNotification() { if (_hubConnection?.State == HubConnectionState.Connected) { await _hubConnection.SendAsync("SendMessage", "hello"); } } }