【发布时间】:2013-10-06 15:23:10
【问题描述】:
在 ASP MVC5 RC 中,我没有让角色系统工作。 我的数据库有一个角色存在的所有需求表,但如果用户在角色中进行校对总是返回 false(没有 SQL 异常或其他东西)!?
我需要在某处为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("string role name") 吗?
-
或者你可以试试:string[] userroles = Roles.GetRolesForUser("username") - 这应该返回一个用户角色数组,你可以循环确定它是否包含特定角色。跨度>
标签: c# asp.net asp.net-mvc-5 asp.net-identity