在ASP MVC5 RC我沒有得到角色系統的工作。 我的數據庫有所有需要表的角色存在,但證明如果用戶在角色中總是返回false(無SQL異常或其他)!角色管理在ASP MVC 5(Microsoft.AspNet.Identity)
我需要在某處激活IPrincipal
的角色系統嗎?
測試代碼:
AccountController accCont = new AccountController();
// check role exist : result = true
var roleExist = await accCont.IdentityManager.Roles.RoleExistsAsync("61c84919-72e2-4114-9520-83a3e5f09de1");
// try find role by name : result = role object
var role = await accCont.IdentityManager.Roles.FindRoleByNameAsync("ProjectAdministrator");
// check with AccountController instance : result = true
var exist = await accCont.IdentityManager.Roles.IsUserInRoleAsync(User.Identity.GetUserId(), role.Id);
// check if current user is in role : result (both) = false????
var inRole = User.IsInRole(role.Id);
var inRole2 = User.IsInRole(role.Name);
我也嘗試從Microsoft.AspNet.Identity.Owin
命名空間打造像IIdentity.GetUserId()
擴展方法的定製過錯。
namespace Microsoft.AspNet.Identity
{
public static class IdentityExtensions
{
public static string IsUserInRole(this IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
ClaimsIdentity identity2 = identity as ClaimsIdentity;
if (identity2 != null)
{
var result = identity2.FindFirstValue(IdentityConfig.Settings.GetAuthenticationOptions().RoleClaimType);
return null; // later result
}
return null;
}
}
}
但要求類型RoleClaimType
結果總是null
:( 我真的堅持了這一點。
謝謝您的幫助!斯特芬
你有沒有試過User.IsInRole(「字符串角色名稱」)? – nocturns2
或者你可以嘗試:string [] userroles = Roles.GetRolesForUser(「username」) - 這應該返回一個userroles中的數組,您可以循環以確定它是否包含特定角色。 – nocturns2