SignalR 核心 如何获取连接参数服务器端



>按照这个答案 如何在集线器连接中发送参数/查询 信令核心

我正在设置客户端:

const connectionHub = new HubConnectionBuilder()
.withUrl(Constants.URL_WEB_SOCKET + '?token=123')
.build();

但是如何获得令牌值服务器端呢?

public override async Task OnConnectedAsync()
{
_connectionId = Context.ConnectionId;
var token = Context.Items["token"]; // this is null
var token2 = Context.QueryString["token"]; // 'HubCallerContext' does not contain a definition for 'QueryString' 
await base.OnConnectedAsync();
}

如果要在.NET Core中获取令牌值,可以使用以下代码:

var httpContext = Context.GetHttpContext();
var tokenValue = httpContext.Request.Query["token"];

您可以在 QueryString 中发送参数。

在客户端中,声明字符串字典和连接

private Dictionary<string, string> _querystringdata = new Dictionary<string, string>();
private HubConnection _connection;
private const string HubUrl = "your hub url";

然后,分配要发送的值

_querystringdata.Add("key", "Value");
_connection = new HubConnection(HubUrl, _querystringdata);

启动连接

if (_connection.State == ConnectionState.Disconnected)
{
// Creating the signalrHub proxy
IHubProxy signalrHub = _connection.CreateHubProxy("SignalrHub");
Console.WriteLine("Initiating Connection");
// starting the signalr connection
_connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected to server");
//Client methods which server can invoke
signalrHub.On<dynamic>("sendMessage", (data) =>
{
Console.WriteLine("Message:- {0}", data);
// do something
});
}
}).Wait(); 
}

然后在服务器 signalR 集线器类中

public override Task OnConnected()
{
try
{
// getting the value sent with query string
var token = Context.QueryString.Get("Key");
// do something like connection mapping etc
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return (base.OnConnected());
}

最新更新