在Asp.Net API Controller中将用户添加到角色时找不到角色?

时间:2017-09-29 14:27:32

标签: c# angularjs asp.net-mvc asp.net-web-api asp.net-identity

所以,就在我最终认为我理解了Microsoft Asp.Net身份角色系统的时候......我遇到了一个新问题......

我有一个可以管理我的角色的工作控制器但是我在视图中遇到了问题所以我决定将angularjs用于我的Web-Apps管理员面板。

在一些黑客行为之后,一切似乎都有效,但现在我正处于一个我根本无法理解的地步。我的过程:

  • 管理员按下一个按钮,该按钮将用户ID(字符串)传递给角度控制器。
  • Angular向我的ApiController发出POST请求,将userID传递给应该授权我的用户的Controller操作。

这是我的API控制器:

public async Task<IHttpActionResult> changeAuth()
    {
        string userID;
        var requestData = HttpContext.Current.Request.InputStream;
        using (StreamReader sr = new StreamReader(requestData))
        {
            userID = sr.ReadToEnd();
        }
        Models.ApplicationUser user;
        try
        {
            user = await UserManager.FindByIdAsync(userID);
            if (user == null)
                throw(new Exception());
        }
        catch(Exception ex)
        {
            return BadRequest("couldn't find user in db");
        }
            foreach(var role in user.Roles)
            {
                testlist.Add(RoleManager.FindById(role.RoleId).Name);
            }
            if (!IsUserInRole(user, authRole))
            {
                IdentityResult res = new IdentityResult();
                try
                {
                    res = await UserManager.AddToRoleAsync(user.Id, authRole.Id);
                }
                catch(Exception ex)
                {
                    return BadRequest(ex);
                }
            }
            if(IsUserInRole(user, authRole)
                return Ok("User is now authorized!");
            else
                return InternalServerError("Adding User to Role failed");
    }
  • 我加载了userID(有效)
  • 我加载了来自HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
  • 的用户UserManager
  • 我对相应的角色( - &gt; authRole)执行相同的操作,找到了这两个角色,我可以在调试器中看到它们的值。
  • 用户还没有角色,所以我执行'watit UserManager.AddToRoleAsync(user.Id,authRole.Id);`...并获得例外:

...

Exception: System.InvalidOperationException: The Role "50ab556b-a8e4-4294-b91c-1f9374c25244" does not exist at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.<AddToRoleAsync>d__3b.MoveNext()

我不知道为什么会这样。事实上我使用的是WebAPI控制器而不是常规控制器吗?也许是因为我使用HttpContext.Current.GetOwinContext()而不是HttpContext.GetOwinContext()来加载用户/角色管理器?但是如果Role- / Usermanager出现问题......当我搜索用户和角色时,它是如何找到用户的,只有当我尝试将用户添加到角色时它才起作用? AddToRoleAsync与我今天使用的方法完全相同,当我注册我的TestUsers以向他们添加角色“NewUser”时......

1 个答案:

答案 0 :(得分:0)

没关系,我在AddToRoleAsync中使用了role.id而不是role.Name .... -___-