按照此答案How to send Parameter/Query in HubConnection SignalR Core
我正在设置客户端:
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();
}
答案 0 :(得分:0)
您可以在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());
}
答案 1 :(得分:0)
如果要在 .net核心中获取令牌值,则可以使用以下代码:
var httpContext = Context.GetHttpContext();
var tokenValue = httpContext.Request.Query["token"];