I am trying to update certain fields of AspNetUser using ASP.NET CORE WEB API using UpdateAsync method. I tried the below but throws an error showing username can't be null. For this case, i want to update phonenumber only.
Controller
public async Task<IActionResult> UpdateUserAync([FromBody] RegisterViewModel model)
{
if (ModelState.IsValid)
{
var result = await _userService.UpdateUserAsync(model);
if (result.IsSuccess)
return Ok(result);
return BadRequest(result);
}
return BadRequest("Some Properties are not valid!");
}
Service
public async Task<UserUpdateResponse> UpdateUserAsync(RegisterViewModel model)
{
var user = await _userManager.FindByEmailAsync(model.Email);
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
if (user == null)
throw new NullReferenceException("Update model is null");
if (phoneNumber!=null)
return new UserUpdateResponse
{
Message = "Sorry you can't update!",
IsSuccess = false,
};
var identityUser = new IdentityUser
{
PhoneNumber = model.PhoneNumber
};
var result = await _userManager.UpdateAsync(identityUser);
if (result.Succeeded)
{
return new UserUpdateResponse
{
Message = "Phone number updated Successfully",
IsSuccess = true,
Errors = result.Errors.Select(e => e.Description)
};
}
return new UserUpdateResponse
{
Message = "Phone number didnot Updated!",
IsSuccess = false,
Errors = result.Errors.Select(e => e.Description)
};
}
Here, I only want to update certain fields based on user email/user id.
ErrorMSG
{
"message": "Phone number didnot Updated!",
"isSuccess": false,
"errors": [
"User name '' is invalid, can only contain letters or digits."
],
"expireDate": null
}
Entity Framework tries to INSERT
this user, not UPDATE
it as you create a new instance of IdentityUser
:
var identityUser = new IdentityUser
{
PhoneNumber = model.PhoneNumber
}
So this is the reason why you've got the error. To UPDATE
the user, you need update user
that you've found by FindByEmailAsync
method:
// Get the existing user from the db
var user = await _userManager.FindByEmailAsync(model.Email);
// Update it with the values from the view model
user.Name = model.Name;
user.Surname = model.Surname;
user.UserName = model.UserName;
user.Email = model.Email;
user.PhoneNumber = model.PhoneNumber;
user.PasswordHash = checkUser.PasswordHash;
// Apply the changes
var result = await _userManager.UpdateAsync(user);