在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