1

I have code in my controller to disable an account. The code was working fine. Now, all of a sudden it isn't.

public async Task<ActionResult> DisableClient(string userId, int disableAccount)
{
    bool disable = (disableAccount != 0);
    ApplicationUser user = UserManager.FindById(userId);
    if (user != null && user.Disabled != disable)
    {
        user.UserName = disable ? DisabledUserName : user.Email;   // Not sure if this is needed
        user.Disabled = disable;
        // Generating a new security stamp invalidates the user's
        // session, effectively locking them out
        if (user.Disabled)
            await UserManager.UpdateSecurityStampAsync(userId);
        await UserManager.UpdateAsync(user);
    }
    return RedirectToAction("Details", "Client", new { userId = userId });
}

ApplicationUser.Disabled was mapping to AspNetUsers.Disabled. But now, I can see the code above setting this property to true, but the value in the database remains false.

I don't understand how this could've changed. Can anyone help explain this?

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • I'm pretty sure you should add context.SaveChanges() – swforlife Feb 20 '19 at 18:19
  • @swforlife: Neither `ApplicationUserManager` or `ApplicationUser` have a `SaveChanges()` method. – Jonathan Wood Feb 20 '19 at 18:23
  • the context inside should have. see link below – swforlife Feb 20 '19 at 18:23
  • @swforlife: Could you clarify *context inside*? I haven't found it. The other question appears to have the context, but Identity uses a different one that I use in my own code. – Jonathan Wood Feb 20 '19 at 18:26
  • my bad, can you post your usermanager aswell? Are you sure your usermanager is using your ApplicationUser I think this is more like what you're looking for https://stackoverflow.com/questions/22652118/disable-user-in-aspnet-identity-2-0/35310691 – swforlife Feb 20 '19 at 18:34
  • @swforlife: Thanks for your help. Ultimately, it helped me determine what was happening. I've answered my own question. – Jonathan Wood Feb 20 '19 at 18:38

1 Answers1

0

I figured it out. I tried adding the following line to ensure the database context was saving the changes.

HttpContext.GetOwinContext().Get<ApplicationDbContext>().SaveChanges();

However, this line caused an exception because my code had produced a duplicate value in an indexed column.

I now assume that my original code was also producing an exception, but it was handled silently. The line above is not needed. As long as there is no hidden exception, my original code works fine. And this explains why it was working but then stopped: Because it had to have two accounts disabled before there was a duplicate that causes the exception.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466