SignalR Client 开始连接时如何设置用户?

SignalR Client How to Set user when start connection?

服务器端:

public override Task OnConnected()
{
    var connectionId = Context.ConnectionId;
    var user = Context.User.Identity.Name; // Context.User is NULL
    return base.OnConnected();
}

客户端(在控制台项目中):

IHubProxy _hub;
string url = @"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("TestHub");
connection.Start().Wait();

当客户端连接到服务器时,我想知道userName和connectionId之间的映射,但是Context.User是NULL。我如何在客户端设置这个值?

使用查询字符串传递您的用户名。

客户端

首先设置查询字符串

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

试试这个

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

使用 asp.netcore 中的 queryString 试试这个 2.1:

客户端(javascript) 在 url 之后设置查询字符串,如下所示:

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

客户端

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

如果您使用基本身份验证,请创建一个新的 System.Net.NetworkCredential

string url = @"http://localhost:8080/";
var connection = new HubConnection(url);

NetworkCredential myCredentials = new NetworkCredential("","","");
myCredentials.Domain = "domain";
myCredentials.UserName = "username";
myCredentials.Password = "passwd";   

connection.Credentials = myCredentials;

_hub = connection.CreateHubProxy("TestHub");


connection.Start().Wait();

参见:https://docs.microsoft.com/en-us/dotnet/api/system.net.networkcredential.username?view=net-6.0