I'm implementing a notification system in my ASP.NET Core API using SignalR and a Blazor client. I have set up a NotificationHub and a custom user ID provider to manage user connections. However, every time I launch my application, I encounter the following error:WebSocket connection to 'wss://localhost:63225/notificationHub?id=LDfet**&access_token=ey**' failed: Code Snippets:NotificationHub:
[Authorize]public class NotificationHub : Hub{ public override Task OnConnectedAsync() { Debug.WriteLine(Context.UserIdentifier); return base.OnConnectedAsync(); }}CustomUserIdProvider:
public class CustomUserIdProvider : IUserIdProvider{ public string? GetUserId(HubConnectionContext connection) { return connection.User?.Identity?.Name; }}Adding a Request with Notification:
public async Task<int> AddEvolutionDemand(EvolutionDto evolutionToAddDto) { var EvolutionDemand = new Evolution(); try { EvolutionDemand = new() { Service_ID = evolutionToAddDto.Service_ID, User_ID = evolutionToAddDto.User_ID, User_Name = evolutionToAddDto.User_Name, Doc_ID = evolutionToAddDto.Doc_ID, Demande_Creation_Date = evolutionToAddDto.Demande_Creation_Date, Demand_Type = evolutionToAddDto.Demand_Type, Demand_Title = evolutionToAddDto.Demand_Title, Demande_Comment = evolutionToAddDto.Demande_Comment, STATUS = evolutionToAddDto.STATUS, Demand_Assigned_ID = evolutionToAddDto.Demand_Assigned_ID, Demand_update_date = evolutionToAddDto.Demand_update_date, Demand_Update_Comment = evolutionToAddDto.Demand_Update_Comment, }; await _kmDbContext.Evolution.AddAsync(EvolutionDemand); await _kmDbContext.SaveChangesAsync(); var UserToNotify = await UserRepository.GetUser(evolutionToAddDto.Demand_Assigned_ID); await HubConntextion.Clients.User(UserToNotify.User_Login).SendAsync("notification", $"{DateTime.Now}"); } catch (Exception ex) { _logger.Error(ex, ErrorMessage, ex.Message); } return EvolutionDemand.Demand_ID; }Blazor Client:
@code { private HubConnection? hubConnection; public int pendingDemandCount { get; set; } = 0; List<string> notifications = []; [Inject] IAccessTokenProvider AccessTokenProvider { get; set; } = default!; protected override async Task OnInitializedAsync() { await base.OnInitializedAsync(); var authState = await AuthenticationStateTask; if (authState.User.Identity != null && authState.User.Identity.IsAuthenticated) { await connectToNotificationHub(); await RefreshPendingDemands(); } } public async Task connectToNotificationHub() { try { if (hubConnection is not null) return; var notificationUrl = "notificationHub"; hubConnection = new HubConnectionBuilder() .WithUrl($"https://localhost:63225/{notificationUrl}", options => { options.AccessTokenProvider = () => GetAccessTokenAsync(); }) .Build(); hubConnection.On<string>("notification", async (message) => { notifications.Add(message); await RefreshPendingDemands(); await InvokeAsync(StateHasChanged); }); await hubConnection.StartAsync(); } catch (Exception ex) { Console.WriteLine($"Error connecting to SignalR hub: {ex.Message}"); Console.WriteLine($"Stack trace: {ex.StackTrace}"); } } private async Task<string?> GetAccessTokenAsync() { var tokenResult = await AccessTokenProvider.RequestAccessToken(); if (tokenResult != null && tokenResult.TryGetToken(out AccessToken accessToken)) { return accessToken.Value; } return null; } private async Task RefreshPendingDemands() { var pendingDemands = await DocumentService.GetPendingDemandsForUser(); pendingDemandCount = pendingDemands?.Count ?? 0; } public async ValueTask DisposeAsync() { if (hubConnection is not null) { await hubConnection.DisposeAsync(); hubConnection = null; } }}What could be causing the WebSocket connection failure, and how can I troubleshoot this issue? I’ve verified that the access_token is correctly generated and that the user is authenticated. Any guidance on resolving this would be greatly appreciated!
I implemented the OnConnectedAsync method in the NotificationHub to log the user identifier and verify if the connection is being established correctly.I ensured that the access token is generated correctly using IAccessTokenProvider in my Blazor client. I log any issues with the token retrieval process.