其他分享
首页 > 其他分享> > 删除用户声明

删除用户声明

作者:互联网

我正在将ASP.NET Identity(v2)与实体框架一起使用.我正在建立一个包含多个复选框的页面,每个复选框代表一个索赔.单击按钮(在我的示例中为SavePrivileges函数),我想根据复选框的状态调整给定用户的声明,即删除未选中的声明,并添加已选中的声明.

添加声明可以正常进行.但是,我似乎无法从用户中删除版权声明.调用manager.RemoveClaim后,我收到一个InvalidOperationException消息,说该集合已更改.即使不修改user.Claims集合,我实际上也会收到此异常.

这是我的简化示例场景:

    protected void SavePrivileges(string userId)
    {
        const string claim1Type = "...";
        const string claim2Type = "...";
        const string claim1Value = "...";
        const string claim2Value = "...";

        var store = new UserStore<IdentityUser>();
        var manager = new UserManager<IdentityUser>(store);
        var user = manager.FindById(userId);

        // Lists to keep track of changes
        var removed = new List<Claim>();
        var added = new List<Claim>();

        bool claim1Checked = CheckBox1.Checked;
        bool claim2Checked = CheckBox2.Checked;

        bool claim1Possesed = user.Claims.FirstOrDefault(claim => claim.ClaimValue == claim1Value &&
                                                                  claim.ClaimType  == claim1Type) != null;
        bool claim2Possesed = user.Claims.FirstOrDefault(claim => claim.ClaimValue == claim2Value &&
                                                                  claim.ClaimType  == claim2Type) != null;

        if (claim1Checked && !claim1Possesed)
        {
            added.Add(new Claim(claim1Type, claim1Value));
        }
        else if (!claim1Checked && claim1Possesed)
        {
            removed.Add(new Claim(claim1Type, claim1Value));
        }
        // + The same for claim2...

        // Remove extra claims
        foreach (Claim claim in removed)
        {
            manager.RemoveClaim(user.Id, claim);
        }
        // Add new claims
        foreach (Claim claim in added)
        {
            IdentityUserClaim identityUserClaim = new IdentityUserClaim { ClaimType = claim.Type, ClaimValue = claim.Value };
            user.Claims.Add(identityUserClaim);
        }

        // Save the result
        var result = manager.Update(user);
        if (result.Succeeded)
        {
            store.Context.SaveChanges();
        }
    }

谢谢你的帮助.

解决方法:

我终于找到了解决方案,但是,它绝不是一成不变的.如果有人提出更好的解决方案,我仍然很高兴看到它.

foreach (Claim claim in removed) {
    var claimCollection = store.Context.Entry(user).Collection(u => u.Claims).CurrentValue;
    var storedClaim = claimCollection.FirstOrDefault(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value && c.UserId == user.Id);
    if (storedClaim != null)
        store.Context.Entry(storedClaim).State = EntityState.Deleted;
}

标签:asp-net-identity,c
来源: https://codeday.me/bug/20191028/1953336.html