[英]Can't find role when adding user to role in Asp.Net API Controller?
So, just when I finally thought I had understood the Microsoft Asp.Net Identity Role System ... I run into a new problem... 因此,当我终于以为自己已经了解了Microsoft Asp.Net身份角色系统时,我遇到了一个新问题……
I have a working controller that does my role management but I had problems in the view so I decided to use angularjs for my Web-Apps Admin-Panel. 我有一个工作控制器来执行角色管理,但视图中存在问题,因此我决定为我的Web-Apps Admin-Panel使用angularjs。
Everything seemed to work after a bit of hacking but now I'm at a point that I don't understand at all. 经过一番黑客攻击后,一切似乎都可以正常工作,但现在我完全不了解。 My process:
我的过程:
Here is my API 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");
}
HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
获得的用户UserManager HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
... ...
Exception: System.InvalidOperationException: The Role "50ab556b-a8e4-4294-b91c-1f9374c25244" does not exist at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.<AddToRoleAsync>d__3b.MoveNext()
I have no clue why this is happening. 我不知道为什么会这样。 Is it the fact that I'm using a WebAPI Controller instead of regular?
我使用的是WebAPI Controller而不是常规的事实吗? Maybe because I use HttpContext.Current.GetOwinContext() instead of HttpContext.GetOwinContext() to load the User/Role Manager?
也许是因为我使用HttpContext.Current.GetOwinContext()而不是HttpContext.GetOwinContext()来加载用户/角色管理器? But if there's something wrong with Role-/Usermanager ... how does it find the user and the role when I search for it, only when I try to add the user to the role it doesn't work?
但是,如果Role- / Usermanager出问题了……当我搜索用户和角色时,仅当我尝试将用户添加到该角色时,它如何找到用户和角色却不起作用? AddToRoleAsync is the very same method I used just today, when I registered my TestUsers to add the role "NewUser" to them ...
AddToRoleAsync是我今天使用的非常相同的方法,当时我注册了TestUsers以向他们添加角色“ NewUser” ...
没关系,我在AddToRoleAsync中使用的是role.id而不是role.Name ...--___-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.