所以,就在我最终认为我理解了Microsoft Asp.Net身份角色系统的时候......我遇到了一个新问题......
我有一个可以管理我的角色的工作控制器但是我在视图中遇到了问题所以我决定将angularjs用于我的Web-Apps管理员面板。
在一些黑客行为之后,一切似乎都有效,但现在我正处于一个我根本无法理解的地步。我的过程:
这是我的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>();
...
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”时......
答案 0 :(得分:0)
没关系,我在AddToRoleAsync中使用了role.id而不是role.Name .... -___-