Open Closed

How to send messages to users using Signalr #7056


User avatar
0
327992883@qq.com created
  • ABP Framework version: v7.2.3
  • UI Type: Blazor Server
  • Database System: EF Core (SQL Server,) /
  • Tiered (for MVC) or Auth Server Separated (for Angular): yes
  • Exception message and full stack trace:
  • Steps to reproduce the issue:
  • This is my code. When I use await _hubContext.Clients.Users(stringUserIds).SendAsync(message.MessageType.ToString(), message); No messages received in blazor page
public async Task SendToUsersAsync<T>(T message) where T : SigalRMessage
 {
     try
     {
         if (!message.UserIds.HasItems())
             return;

         var stringUserIds = message.UserIds.Where(s => !s.IsNullOrEmpty()).Select(x => x.Value.ToString()).ToList();
         await _hubContext.Clients.Users(stringUserIds).SendAsync(message.MessageType.ToString(), message);
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "error");
     }
 }
protected override async Task OnInitializedAsync()
{
    SetTableOption();

    var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
    var user = authState.User;
    var claims = CurrentUser.GetAllClaims();
    var headers = new Dictionary<string, string>();
    foreach (var claim in claims)
    {
        if (!headers.Keys.Contains(claim.Type))
            headers.Add(claim.Type, claim.Value);
    }

    _userToken = user.FindFirstValue("access_token"); 

    var signalRUrl = "wss://localhost:44320".EnsureEndsWith('/') + Configuration["HubUrl"].TrimStart('/');

    HubConnection = new HubConnectionBuilder()
        .WithUrl(signalRUrl, options =>
        {
            options.Headers = headers;
            options.AccessTokenProvider = () => Task.FromResult(_userToken);
        }).WithAutomaticReconnect().Build();

    // 2. 定义客户端方法以接收服务器消息
    HubConnection.On<SigalRMessage<Dictionary<string, string>>>(SigalRMessageTypeEnum.OrderSyncSuccess.ToString(), async message =>
    {
        await JSRuntime.InvokeVoidAsync("console.log", $"收到sigalr消息:{message.ToJson()} {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
        StateHasChanged(); 
    });

    await HubConnection.StartAsync();
}

I looked at some sample code

 [Inject]
    protected IAbpAccessTokenProvider AccessTokenProvider { get; set; }

    [Inject]
    protected IOptions<ChatBlazorMauiBlazorOptions> ChatBlazorMauiBlazorOptions { get; set; }

    [Inject]
    protected IOptions<AbpRemoteServiceOptions> AbpRemoteServiceOptions { get; set; }

    protected async override Task SetChatHubConnectionAsync()
    {
        var accessToken = await AccessTokenProvider.GetTokenAsync();

        var signalrUrl = ChatBlazorMauiBlazorOptions.Value.SignalrUrl ?? AbpRemoteServiceOptions.Value.RemoteServices.Default.BaseUrl;

        HubConnection = new HubConnectionBuilder()
            .WithUrl(signalrUrl.EnsureEndsWith('/') + "signalr-hubs/chat", options =>
            {
                options.AccessTokenProvider = () => Task.FromResult(accessToken);
            })
            .Build();
    }

But IAbpAccessTokenProvider does not seem to exist in abp7.2.3 version


3 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    You can try to get access token from HttpContext in 7.2.3

    var httpContext = HttpContextAccessor?.HttpContext;
    if (httpContext == null)
    {
        return null;
    }
    
    return await httpContext.GetTokenAsync("access_token");
    
  • User Avatar
    0
    327992883@qq.com created

    hi

    You can try to get access token from HttpContext in 7.2.3

    var httpContext = HttpContextAccessor?.HttpContext; 
    if (httpContext == null) 
    { 
        return null; 
    } 
     
    return await httpContext.GetTokenAsync("access_token"); 
    

    I use this method to get the token, but the result is null

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Is your SendToUsersAsync code's website and localhost:44320 the same website?

    Can you share some code to reproduce in a new template project?

Made with ❤️ on ABP v9.1.0-preview. Updated on November 01, 2024, 05:35