使用 asp.net 身份更新用户角色 [英] Updating user role using asp.net identity

查看:24
本文介绍了使用 asp.net 身份更新用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.使用下面的代码更改用户的当前角色时,我收到如下消息的异常:

I have the following problem. While using the following code below to change the user's current role i am getting an exception with the message like below:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public virtual ActionResult Edit(User user, string role)
    {
        if (ModelState.IsValid)
        {
            var oldUser = DB.Users.SingleOrDefault(u => u.Id == user.Id);
            var oldRoleId = oldUser.Roles.SingleOrDefault().RoleId;
            var oldRoleName = DB.Roles.SingleOrDefault(r => r.Id == oldRoleId).Name;
            if (oldRoleName != role)
            {
                Manager.RemoveFromRole(user.Id, oldRoleName);
                Manager.AddToRole(user.Id, role);
            }
            DB.Entry(user).State = EntityState.Modified;

            return RedirectToAction(MVC.User.Index());
        }
        return View(user);
    }

附加类型为Models.Entities.User"的实体失败,因为相同类型的另一个实体已经具有相同的主键值.如果图中的任何实体具有冲突的键值,则在使用附加"方法或将实体的状态设置为未更改"或已修改"时,可能会发生这种情况.这可能是因为某些实体是新的,尚未收到数据库生成的键值.在这种情况下,使用添加"方法或添加"实体状态来跟踪图形,然后根据需要将非新实体的状态设置为未更改"或已修改".

有人知道这个问题的好的解决方案吗?

Does anybody know a good solution to this problem ?

推荐答案

问题是您的 Manager 和 DB 没有使用相同的 DbContext.因此,当您将数据库上下文中的用户发送到管理器时,它会将其作为新"用户处理 - 然后您无法将其从角色中删除.你有两种方法可以到这里.最简单的方法是从您的经理那里获取用户.

The problem is that your Manager and DB doesn't use the same DbContext. So when you send an user from the context of your DB to the Manager it will handle it as a "new" one - and then you cant remove it from the role. You have two ways to go here. The easiest is to get the User from your Manager.

[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult Edit(User user, string role)
{
    if (ModelState.IsValid)
    {
        // THIS LINE IS IMPORTANT
        var oldUser = Manager.FindById(user.Id);
        var oldRoleId = oldUser.Roles.SingleOrDefault().RoleId;
        var oldRoleName = DB.Roles.SingleOrDefault(r => r.Id == oldRoleId).Name;

        if (oldRoleName != role)
        {
            Manager.RemoveFromRole(user.Id, oldRoleName);
            Manager.AddToRole(user.Id, role);
        }
        DB.Entry(user).State = EntityState.Modified;

        return RedirectToAction(MVC.User.Index());
    }
    return View(user);
}

更优雅的方法是开始使用像 AutoFac (https://code.google.com/p/autofac/wiki/MvcIntegration) 并将您的 DbContext 设置为 InstancePerApiRequest.

The more elegant way is to start using an DI-framework like AutoFac (https://code.google.com/p/autofac/wiki/MvcIntegration) and set your DbContext as InstancePerApiRequest.

builder.RegisterType<YourDbContext>().As<DbContext>().InstancePerApiRequest();

这篇关于使用 asp.net 身份更新用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆