I am trying to update user details from a SQL database using ASP.NET Core MVC and Angular. I want to update the user without sending the UserID to the API so i have to get the UserId in the PUT method. I used Entity and Identity to create the database.
With the following code I am getting this error:
Code: "ConcurrencyFailure"
Description: "Optimistic concurrency failure, object has been modified."
How can i make this works?
PUT Method
[HttpPut]
[Route("Update")]
//api/ApplicationUser/Update
public async Task<Object> PutApplicationUser(UserAccountModel model)
{
var user = _userManager.GetUserId(HttpContext.User);
var applicationUser = new UserAccount()
{
UserName = model.UserName,
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email,
PhoneNumber = model.PhoneNumber,
VerificationCode = "",
ExpCode = new DateTime(2020, 8, 18),
SecurityStamp = Guid.NewGuid().ToString()
};
try
{
var result = await _userManager.UpdateAsync(applicationUser);
return result;
}
catch (Exception ex)
{
throw ex;
}
}
UserAccount model
public class UserAccount : IdentityUser
{
[Column(TypeName = "nvarchar(30)")]
public string FirstName { get; set; }
[Column(TypeName = "nvarchar(30)")]
public string LastName { get; set; }
[Column(TypeName = "nvarchar(30)")]
public string VerificationCode { get; set; }
[Column(TypeName = "smalldatetime")]
public DateTime ExpCode { get; set; }
public virtual ICollection<File> File { get; set; }
public virtual ICollection<Folder> Folder { get; set; }
}
Try getting ConcurrencyStamp
for this user and set it to your update model:
var user = _userManager.GetUserId(HttpContext.User);
var currStamp = ... // somehow get current stamp
var applicationUser = new UserAccount()
{
...
ConcurrencyStamp = currStamp
};
Or just use UserManager<TUser>.GetUserAsync
and update fields on returned user:
var user = await _userManager.GetUserAsync(HttpContext.User);
user.UserName = model.UserName;
.....
var result = await _userManager.UpdateAsync(user);
I think you should update the record that exist. This works:
string user = User.Claims.First(c => c.Type == "UserID").Value;
var userModel = await _userManager.FindByIdAsync(user);
userModel.model.UserName;
userModel.FirstName = model.FirstName;
userModel.LastName = model.LastName;
userModel.Email = model.Email;
userModel.PhoneNumber = model.PhoneNumber;
userModel.VerificationCode = "";
userModel.ExpCode = new DateTime(2020, 8, 18);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.