所以,當我最終以爲我已經理解了微軟Asp.Net身份角色系統...我遇到了一個新問題...將用戶添加到Asp.Net API控制器中的角色時找不到角色?
我有一個工作控制器,可以完成我的角色管理,但是我遇到了問題在視圖中,所以我決定爲我的Web-Apps管理面板使用angularjs。
一切似乎工作後一些黑客,但現在我在一個我根本不明白的點。我的過程:
- 管理員按下一個按鈕,它將用戶ID(字符串)傳遞給角度控制器。
- Angular向我的ApiController發送POST請求,將用戶ID傳遞給應該授權我的用戶的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");
}
- 我加載用戶ID(工作)
- 我加載用戶的UserManager,我從
HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
- 了我做同樣的與相應的角色( - > authRole),這兩個都被發現,我可以在調試器中看到它們的值。
- 用戶沒有作用,所以我執行'await 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」時...
爲什麼你不將userId作爲http請求中的參數傳遞並將ID作爲參數添加到WebApi控制器中?另外,爲什麼你拋出一個異常,如果用戶== null並抓住它?返回BadRequest而不是在異常處理程序中描述此邏輯更容易嗎? – OlegI
還要了解添加請添加UserManager.AddToRoleAsync()方法正文,因爲這是您從 – OlegI
得到例外的地方您正在角色和authRole之間交換部分代碼。我看不到authRole的定義。 –