Когда один сеанс увеличивает значение / counter, все сеансы уведомляются об этом и обновляют отображаемое значение. Все это работает.
Я не понимаю, почему в инструментах разработчика браузера нет соединения с настроенным URL-адресом хаба. Для /_blazor существует только стандартный веб-сокет сервера Blazor.
Код для Counter.razor обновляется следующим образом:
Код: Выделить всё
Counter
Counter
Current count: @currentCount
Click me
@code {
private int currentCount = 0;
private HubConnection _hubConnection;
public async ValueTask DisposeAsync()
{
await _hubConnection.DisposeAsync();
}
protected override async Task OnInitializedAsync()
{
_hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri(CounterHub.HubUrl))
.Build();
_hubConnection.On(CounterHub.CounterUpdatedMethod, HandleCounterUpdated);
await _hubConnection.StartAsync();
}
private void HandleCounterUpdated(CounterNotification notification)
{
currentCount = notification.Counter;
InvokeAsync(StateHasChanged);
}
private async Task IncrementCount()
{
await CounterHubContext.Clients.All.SendAsync(CounterHub.CounterUpdatedMethod, new CounterNotification(currentCount + 1));
}
}
Код: Выделить всё
CounterHub.cs
Код: Выделить всё
public class CounterHub : Hub
{
public const string HubUrl = "/counter-notifications";
public const string CounterUpdatedMethod = "CounterUpdated";
public override Task OnConnectedAsync()
{
Console.WriteLine("{0} connected", Context.ConnectionId);
return base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? e)
{
Console.WriteLine("{0} disconnected", Context.ConnectionId);
await base.OnDisconnectedAsync(e);
}
}
Код: Выделить всё
CounterNotification.cs
Код: Выделить всё
public record CounterNotification(int Counter)
{
public CounterNotification() : this(0) { }
}
Код: Выделить всё
builder.Services.AddSignalR();
builder.Services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
["application/octet-stream"]);
});
app.UseResponseCompression();
app.MapHub(CounterHub.HubUrl);

Подробнее здесь: https://stackoverflow.com/questions/792 ... ignalr-hub