天道酬勤,学无止境

SignalR 客户端如何在开始连接时设置用户?(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。 如何在客户端设置此值?

回答1

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

客户

首先设置查询字符串

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

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

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

客户

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);
回答4

试试这个

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

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐