SignalR Client How to Set user when start connection?

孤者浪人 提交于 2019-12-03 07:17:01

Pass your username using query string.

Client

First set query string

string url = @"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("TestHub");
connection.qs = { 'username' : 'anik' };
connection.Start().Wait();

Server

public override Task OnConnected()
{
    var username= Context.QueryString['username'];
    return base.OnConnected();
}

try this with queryString in asp.netcore 2.1:

Client (javascript) set query string after url like follow:

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

Server

public override Task OnConnectedAsync()
    {
        var  username = Context.GetHttpContext().Request.Query["username"];
        // username = xxxx
        return base.OnConnectedAsync();
    }

Client

var connection = new HubConnection(<YOUR_URL>);
connection.Headers.Add("username", "maria");
var myHub = connection.CreateHubProxy("MyHub");

Server

string username = Context.Headers.Get("username");
Console.WriteLine("New client connection - " + username);

try this

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

Server

public override Task OnConnected()
{
  var connectionId = Context.ConnectionId;
  var username= Context.QueryString["username"]; //here you will receive naveed as username

  return base.OnConnected();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!