【问题标题】:Why does @User.IsInRole always return false in _Layout.cshtml为什么@User.IsInRole 总是在_Layout.cshtml 中返回false
【发布时间】:2019-05-15 14:06:05
【问题描述】:

我正在使用 Razor-Pages 开发网络应用程序。在我的 _Layout.cshtml 文件中,我想根据当前用户的角色更改菜单。 因此,我使用User.IsInRole(string role),但它总是返回 false。

在类似的问题中,我读到无法在登录后立即检索用户角色。但是,我不明白为什么会这样。

我的代码:

@if (User.IsInRole(Roles.Admin.ToString())) {
  <li><a asp-page="/AdminMenuPoint">Admin Menu</a>a/li>
}

我的角色枚举:

public enum Roles {
  Supervisor, Admin
};

总结一下:为什么User.IsInRole() 不能用于我的主页(登录后)?

提前致谢。

【问题讨论】:

  • 你在 web.config 中有 enabled="true" 和 roleManager 吗?
  • 您是否连接了 ASP 身份以使用您的 Roles 枚举?在您的启动文件的ConfigureServices 方法中应该有类似services.AddIdentity&lt;User, Role&gt;() 的内容。
  • @LeonardoSeccia 我刚刚做了。它仍然不起作用。
  • @st_stefanov 的评论尝试:&lt;modules&gt; &lt;remove name="FormsAuthenticationModule" /&gt; &lt;remove name="RoleManager" /&gt; &lt;/modules&gt;

标签: c# asp.net asp.net-core razor


【解决方案1】:

如果你使用 .Net Core 你需要设置:

  1. 在 Startup.cs 中添加身份服务

已编辑

services.AddDefaultIdentity<ApplicationUser>()
   .AddRoles<IdentityRole>() // <-- Add this line
    .AddEntityFrameworkStores<ApplicationDbContext>();

根据this discussion on GitHub,让角色和声明显示在 cookie 中涉及要么恢复到 service.AddIdentity 初始化代码,或者坚持使用 service.AddDefaultIdentity 并添加这行代码给ConfigureServices:

// Add Role claims to the User object
// See: https://github.com/aspnet/Identity/issues/1813#issuecomment-420066501
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>>();
  1. 创建角色并为角色分配用户
private async Task CreateUserRoles(IServiceProvider serviceProvider)
{
 var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
 var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

 IdentityResult roleResult;
 //Adding Admin Role
 var roleCheck = await RoleManager.RoleExistsAsync("Admin");
 if (!roleCheck)
 {
 //create the roles and seed them to the database
 roleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
 }
 //Assign Admin role to the main User here we have given our newly registered 
 //login id for Admin management
 ApplicationUser user = await UserManager.FindByEmailAsync("syedshanumcain@gmail.com");
 var User = new ApplicationUser();
 await UserManager.AddToRoleAsync(user, "Admin");
}

【讨论】:

  • 谢谢,但这不是我的问题。用户及其角色的播种似乎不是问题
  • @Jimmy 是分配给表 ASPNetUserRoles 角色的用户吗?
  • 感谢您的帮助。我刚刚在我的数据库中检查了AspNetUserRoles,数据播种工作正常。所以,是的,用户被正确分配到他们各自的角色......
  • 嗨@Jimmy,您尝试将其添加到服务中吗?services.AddScoped&lt;IUserClaimsPrincipalFactory&lt;ApplicationUser&gt;, UserClaimsPrincipalFactory&lt;ApplicationUser, IdentityRole&gt;&gt;();
  • 非常感谢你!我没有看到你编辑了你的解决方案。我刚刚添加了services.AddScoped&lt;IUserClaimsPrincipalFactory&lt;ApplicationUser&gt;, UserClaimsPrincipalFactory&lt;ApplicationUser, IdentityRole&gt;&gt;();,它就像一个魅力。谢谢大佬:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-15
  • 2015-08-02
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多