本文介绍了如何在HubConnection SignalR Core 2.1中发送参数/查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将参数发送到与 signalr

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();

在服务器端,我从HttpContext获取此参数:

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();
        }

GetHttpContext().Request.Query ["token"] 为空,因为组名收到默认",如以下代码所示

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";

我忘记了一步吗?我正在使用aspnetcore 2.1

am I forgetting a step?I am using aspnetcore 2.1

推荐答案

从您的代码中,我认为您使用的是ASP.NET Core SignalR .NET客户端库.以下是在基于控制台的应用程序中使用.net客户端的有效演示.您的代码.

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.

控制台应用程序

1.从 Manage NuGet Package

2.连接到集线器

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

await connection.StartAsync();

SignalR集线器端

您可以参考这篇文章设置您的SignalR集线器.

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

1.设置SignalR路由

1.Setup SignalR routes

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

2.Hub类:

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.

这篇关于如何在HubConnection SignalR Core 2.1中发送参数/查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:46