服务器端:
public override Task OnConnected()
{
var connectionId = Context.ConnectionId;
var user = Context.User.Identity.Name; // Context.User is NULL
return base.OnConnected();
}
客户端(在Console项目中):
IHubProxy _hub;
string url = @"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("TestHub");
connection.Start().Wait();
当客户端连接到服务器时,我想知道userName和connectionId之间的映射,但Context.User
为NULL。如何在客户端设置此值?
答案 0 :(得分:4)
使用查询字符串传递您的用户名。
<强>客户端强>
首先设置查询字符串
string url = @"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("TestHub");
connection.qs = { 'username' : 'anik' };
connection.Start().Wait();
服务器强>
public override Task OnConnected()
{
var username= Context.QueryString['username'];
return base.OnConnected();
}
答案 1 :(得分:1)
使用 asp.netcore 2.1 中的queryString尝试此操作:
客户端(javascript) 在网址后设置查询字符串,如下所示:
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:10499/chathub?username=xxxx").build();
connection.start().then(function ()
{
// do some thing here ...
}).catch(function (err)
{
console.error(err.toString());
});
.
.
.
服务器
public override Task OnConnectedAsync()
{
var username = Context.GetHttpContext().Request.Query["username"];
// username = xxxx
return base.OnConnectedAsync();
}
答案 2 :(得分:0)
试试这个
客户(C#)
//Enter query string
var querystringData = new Dictionary<string, string>();
querystringData.Add("username", "naveed");
IHubProxy _hub;
string url = @"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("TestHub");
connection.Start().Wait();
connection.Start().Wait();
服务器强>
public override Task OnConnected()
{
var connectionId = Context.ConnectionId;
var username= Context.QueryString["username"]; //here you will receive naveed as username
return base.OnConnected();
}
答案 3 :(得分:0)
客户
var connection = new HubConnection(<YOUR_URL>);
connection.Headers.Add("username", "maria");
var myHub = connection.CreateHubProxy("MyHub");
服务器
string username = Context.Headers.Get("username");
Console.WriteLine("New client connection - " + username);