.net core SignalR Core如何在服务器端获取连接参数
下面是答案 我正在设置客户端:.net core SignalR Core如何在服务器端获取连接参数,.net-core,signalr,.net Core,Signalr,下面是答案 我正在设置客户端: const connectionHub = new HubConnectionBuilder() .withUrl(Constants.URL_WEB_SOCKET + '?token=123') .build(); 但是如何从服务器端获取令牌值呢 public override async Task OnConnectedAsync() { _connectionId = Context.ConnectionId; var token = C
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();
}
您可以在QueryString中发送参数 在客户端中,声明字符串字典和连接
private Dictionary<string, string> _querystringdata = new Dictionary<string, string>();
private HubConnection _connection;
private const string HubUrl = "your hub url";
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();
}
启动连接
private Dictionary<string, string> _querystringdata = new Dictionary<string, string>();
private HubConnection _connection;
private const string HubUrl = "your hub url";
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();
}
如果要在.net core中获取令牌值,可以使用以下代码:
var httpContext = Context.GetHttpContext();
var tokenValue = httpContext.Request.Query["token"];
不,Constants.URL\u WEB\u SOCKET是我的WEB套接字URL(即)。上下文不包含QueryString的定义,这是因为您没有在客户端中分配QueryString。我已经更新了答案。希望这有帮助。