Search code examples
asp.netasp.net-web-apiasp.net-identity

ASP.NET Identity UserManager UpdateAsync return null


I would like to update the user profile. For this purpose,I wrote "Change Profile" method in web api.I have a problem with updating user data because "UpdateAsync" returns all the time null.

ChangeProfile

[HttpPost]
[Route("api/ChangeProfile")]
[ResponseType(typeof(AccountModel))]
public async Task<IHttpActionResult> ChangeProfile([FromBody]AccountModel model)
{
    var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
    var manager = new UserManager<ApplicationUser>(userStore);
    var user = await manager.FindByNameAsync(model.UserName);
    if (user != null)
    {
        var updateUser = new ApplicationUser()
        {   UserName = model.UserName,
            Email = model.Email,
            FirstName = model.FirstName,
            LastName = model.LastName,

        };

        IdentityResult result = await manager.UpdateAsync(updateUser);

        return Ok(result);
    }
    else
    {
        return NotFound();
    }
}

AccountModel:

  public class AccountModel
{
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string LoggedOn { get; set; }
    public string Roles { get; set; }
}

Any help or suggestion is welcome.


Solution

  • Firstly you need go one more step on your debugging.

    In addition, instead of creating a new AplicationUser, you must update the fields of the user that was retrieved from the database.

     if (user != null)
     {        
        user.UserName = model.UserName,
        user.Email = model.Email,
        user.FirstName = model.FirstName,
        user.LastName = model.LastName,
     };
    
     IdentityResult result = await manager.UpdateAsync(updateUser);
     return Ok(result);
     }
    

    Regards.