John Schultz John Schultz - 3 months ago 21
C# Question

Unable to update an identity user in mvc5

I am attempting to lockout a user in MVC 5 using ASP.NET Identity. I have followed suggestion from other SO posts (which all basically say the same thing) by doing the following:

var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var manager = new ApplicationUserManager(store);
var user = new ApplicationUser() {
Id = form["AspNetUserID"],
LockoutEnabled = true,
LockoutEndDateUtc = DateTime.UtcNow.AddYears(100)
};
IdentityResult result = await manager.UpdateAsync(user);
var context = store.Context;
context.SaveChanges();

return RedirectToAction(actionName: "Index", controllerName: "SiteUsersAdmin");


I've stepped through the above code with a break point at the return line to find out the error and I keep getting either
Name cannot be null or empty
or
{Email/UserName} is already selected


Who do I lock this account out or even unlock it in the future?

Answer

Here is some pseudocode....

var user = UserManager.FindById(form["AspNetUserID"]);
user.LockoutEnabled = true;
user.LockoutEndDateUtc = DateTime.UtcNow.AddYears(100)};

var result = await manager.UpdateAsync(user);

if (claimResult.Succeeded)
{
    //success
}
else
{
    //something went wrong
}
Comments