ASP MVC 5中的角色管理(Microsoft.AspNet.Identity)

在ASP MVC5 RC我没有让角色系统工作。 我的数据库有所有需要的表存在一个角色,但校对用户是否在角色中总是返回false(没有SQLexception或其他东西)!

我是否需要在某处激活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 :(我真的很RoleClaimType

谢谢您的帮助! 斯特芬

我正在努力了解如何在MVC 5中使用角色,这就是我带到这里的原因。 我无法回答您的问题,但请查看此链接。 下载的解决方案开箱即用,我已经能够剪切并粘贴一些代码并使其在我自己的应用程序中运行。 现在我正在努力完全理解它在做什么。

http://www.typecastexception.com/post/2013/11/11/Extending-Identity-Accounts-and-Implementing-Role-Based-Authentication-in-ASPNET-MVC-5.aspx

它可能无法解答您的问题,但至少它是一个完全可行的解决方案,实际上可以正常工作,没有太多的麻烦,所以这是一个很好的起点。

User.IsInRole基本上是查看当前登录用户的声明。 你的逻辑符号是什么样的? 这就是负责将cookie变成用户身份的原因。 这需要正确设置Role声明才能使IsInRole方法正常工作。