How to send Parameter/Query in HubConnection SignalR Core 2.1

为君一笑 提交于 2021-02-10 14:50:32

问题


I'm trying to send parameters into connection to signalr

Connection = new HubConnectionBuilder()
                .WithUrl("https://familyapp.azurewebsites.net/StoreHub?token=123")
                .Build();

            await Connection.StartAsync();

In my server side i take this parameter from HttpContext:

 public override async Task OnConnectedAsync()
        {
            var group = Context.GetHttpContext().Request.Query["token"];

            string value = !string.IsNullOrEmpty(group.ToString()) ? group.ToString() : "default";

            await Groups.AddToGroupAsync(Context.ConnectionId, value);
            await base.OnConnectedAsync();              
        }

but GetHttpContext ().Request.Query["token"] is null, because the group name receives "default" as indicated by the following code

string value = !string.IsNullOrEmpty(group.ToString()) ? group.ToString() : "default";

am I forgetting a step? I am using aspnetcore 2.1


回答1:


From your code , I think that you use ASP.NET Core SignalR .NET client library .Here is a working demo using .net client in console app based on your code.

Console app

1.Install the client library Microsoft.AspNetCore.SignalR.Client with version 3.1.3 from Manage NuGet Package

2.connect to hub

var connection = new HubConnectionBuilder()
            .WithUrl("http://localhost:5000/chatHub?token=123")
            .Build();

await connection.StartAsync();

SignalR hub side

You could refer to this article to setup your SignalR hub.

1.Setup SignalR routes

app.UseSignalR(routes =>
 {
    routes.MapHub<ChatHub>("/chatHub");
 });

2.Hub class:

public class ChatHub:Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }

    public override async Task OnConnectedAsync()
    {
        var group = Context.GetHttpContext().Request.Query["token"];

        string value = !string.IsNullOrEmpty(group.ToString()) ? group.ToString() : "default";

        await Groups.AddToGroupAsync(Context.ConnectionId, value);
        await base.OnConnectedAsync();
    }
}

Here is my demo link , you could refer to.



来源:https://stackoverflow.com/questions/61232651/how-to-send-parameter-query-in-hubconnection-signalr-core-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!