Home > Enterprise >  Cannot access a disposed object.\nObject name: 'AsyncCursor
Cannot access a disposed object.\nObject name: 'AsyncCursor

Time:11-08

Trying to return Ok response but getting the exception:

Cannot access a disposed object.\nObject name: 'AsyncCursor

Getting this on first line in if condition

        var users = await _userCollection.FindAsync(user => user.Phone == loginUser.phone);

        // if user found then login 
        // else create empty doc

        if (users.ToList().Count > 0)
        {
            var user = await users.FirstAsync();
            string token = new ShirtDeck.Utils.JwtUtil(configuration).GenerateJWT(user);
            return Ok(new { user = user, token = token });
        }

Expected to read the first document from the list.

CodePudding user response:

when you call ToList, effectively you close cursor (users), so you should stop working with this cursor after that and proceed working with the cursor result (which you currently ignore).

CodePudding user response:

So it is solved, I saved the result in a list and used that:

var users = await _userCollection.FindAsync(user => user.Phone == loginUser.phone);

    var userList = users.ToList(); // saved result to list
    // if user found then login 
    // else create empty doc
    if (userList.Count > 0)
    {
        var user = userList.First();
        string token = new ShirtDeck.Utils.JwtUtil(configuration).GenerateJWT(user);
        return Ok(new { user = user, token = token });
    }
  • Related