I have the following model and claims:
var bm = new UserProfileUpdateModel
{
LastName = "new",
FirstName = "name",
};
List<Claim> claims = new List<Claim>
{
new Claim("family_name", bm.LastName),
new Claim("given_name", bm.FirstName),
};
In the .NET Core 3.1 application, I am going to remove all the matched claims using _userManager.RemoveClaimsAsync() first and then add the new corresponding claim in claims using _userManager.AddClaimAsync().
Problem:
When I trying to loop the items in claims and do the remove/add, it works.
foreach(var c in claims)
{
// principal is a ClaimsPrincipal
var list = principal.Claims.Where(currC => currC.Type == c.Type).ToList();
var removeResult = await _userManager.RemoveClaimsAsync(user, list);
if(removeResult.Succeeded)
{
var addResult = await _userManager.AddClaimAsync(user, c);
}
}
However, when I switched to use ForEach(),
claims.ForEach(async c =>
{
// principal is a ClaimsPrincipal
var list = principal.Claims.Where(currC => currC.Type == c.Type).ToList();
var removeResult = await _userManager.RemoveClaimsAsync(user, list);
if(removeResult.Succeeded)
{
var addResult = await _userManager.AddClaimAsync(user, c);
}
});
The application will throw an exception telling me A second operation started on this context before a previous operation completed.
So the question is, what happened when I call foreach() and ForEach()? And why only ForEach() will cause the exception?
