获取对象引用未设置为SignalR OnDisconnected内的对象实例

时间:2017-06-01 08:33:38

标签: asp.net-mvc signalr

我正在尝试按用户名获取用户,我的代码在OnConnected方法内部工作,但在OnDisconnected我得到Object reference is not set to an instance of an object这是我的代码:

在这里工作:

public override async Task OnConnected()
{
    var id = Context.ConnectionId;
    var userName = Context.User.Identity.Name;
    var connectedUser = new ChatUserModel();

    var existingUserResponse = await _client.GetAsync("chats/users/" + userName + "/");
    if (existingUserResponse.IsSuccessStatusCode)
    {
        var existingUserResult = existingUserResponse.Content.ReadAsStringAsync().Result;

        var existingUser = JsonConvert.DeserializeObject<ChatUserModel>(existingUserResult);
            existingUser.connectionId = id;
        connectedUser = await AddOrUpdateUser(existingUser);
    }

    var response = await _client.GetAsync("chats/users");
    var result = response.Content.ReadAsStringAsync().Result;
    var users = JsonConvert.DeserializeObject<List<ChatUserModel>>(result);

    Clients.Client(id).userConnected(users);
}

但不在这里:

public override async Task OnDisconnected(bool stopCalled)
{
    var userName = Context.User.Identity.Name;

    try
    {
        var response = await _client.GetAsync("chats/users/" + userName + "/");
    }
    catch (Exception ex)
    {
        string msg = ex.Message;
    }
    //var existingUserResult = existingUserResponse.Content.ReadAsStringAsync().Result;
    //var existingUser = JsonConvert.DeserializeObject<ChatUserModel>(existingUserResult);
    //existingUser.connectionId = "";

    //var connectedUser = await AddOrUpdateUser(existingUser);
}

1 个答案:

答案 0 :(得分:0)

OnDisconnect方法是从服务器而不是从客户端调用,因为User是null。

要处理这种情况,您应该将connectionIds与用户匹配并保存在某处,在OnDisconnect中,您可以通过ConnectionId与用户联系

public override async Task OnConnected()
{
    var id = Context.ConnectionId;
    var userName = Context.User.Identity.Name;
    SaveUserToDb(id,userName);// 
    // other codes
}

public override async Task OnDisconnected(bool stopCalled)
{
    var id = Context.ConnectionId;
    var userName = GetUserNameFromDB(id);

    // and now you have your username 
}