SignalR Client How to Set user when start connection?

前端 未结 4 1427
走了就别回头了
走了就别回头了 2021-02-04 09:46

Server side:

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


        
4条回答
  •  星月不相逢
    2021-02-04 10:01

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

提交回复
热议问题