Asp.net core 如何在Asp.net Identity 3.0和MVC 6中启用角色?

Asp.net core 如何在Asp.net Identity 3.0和MVC 6中启用角色?,asp.net-core,asp.net-core-mvc,asp.net-identity-3,Asp.net Core,Asp.net Core Mvc,Asp.net Identity 3,我不确定我是否遗漏了什么。默认情况下,User.IsInRole()即使用户确实具有某些角色,也不起作用 我没有自己的角色存储实现。我假设默认的应该有效。在Startup.cs中,我是否需要做一些特殊的事情来让角色正常工作?我使用的是mvc 6 beta 2默认模板。如果我添加这样的角色,用户.IsInRole()将无法工作: public MyController( UserManager<ApplicationUser> userManager, SignInMa

我不确定我是否遗漏了什么。默认情况下,
User.IsInRole()
即使用户确实具有某些角色,也不起作用

我没有自己的角色存储实现。我假设默认的应该有效。在
Startup.cs
中,我是否需要做一些特殊的事情来让角色正常工作?我使用的是mvc 6 beta 2默认模板。

如果我添加这样的角色,
用户.IsInRole()
将无法工作:

public MyController(
    UserManager<ApplicationUser> userManager,
    SignInManager<ApplicationUser> signInManager)
{
    _userManager = userManager;
    _signInManager = signInManager;
}
wait UserManager.AddToRoleAsync(用户,“Admin”)

但如果我这样做,它确实有效:


wait UserManager.addClaimesync(用户,索赔:新索赔(ClaimTypes.Role.ToString(),“Admin”)

看起来您正在将Asp.NET标识与最新的Asp.NET 5内容一起使用。我使用的是相同的(目前使用的是RC1)。我有一个类似的问题,经过一些挖掘,我通过使用
SignInManager
RefreshSignInAsync()
方法找到了一个解决方案

请注意,为了获得
UserManager
SignInManager
的实例,我使用依赖项注入,因此控制器的构造函数如下所示:

public MyController(
    UserManager<ApplicationUser> userManager,
    SignInManager<ApplicationUser> signInManager)
{
    _userManager = userManager;
    _signInManager = signInManager;
}
你需要的注意事项

using System.Security.Claims;
对于
GetUserId()
扩展方法

所以我学到的最重要的东西就是使用
UserManager
AddToRoleAsync
signingmanager
RefreshSignInAsync
。第一个将向AspNetUserRoles表中添加一行。第二个刷新cookie,当浏览器发出下一个请求时,cookie将显示该用户处于该角色

另外,我在Startup.cs中添加了一个名为
EnsureRoles()
的方法。我在调用
Configure(IApplicationBuilder应用程序、IHostingEnvironment env、ILoggerFactory)中的
app.UseIdentity()
后立即调用它。下面是
Configure()
中的一个小插曲:

这里是
EnsureRoles()

专用异步任务EnsureRoles(IApplicationBuilder应用程序、ILoggerFactory loggerFactory)
{
ILogger logger=loggerFactory.CreateLogger();
RoleManager RoleManager=app.ApplicationServices.GetService();
字符串[]roleNames={“TheRole”,“AnotherRole”};
foreach(roleNames中的字符串roleName)
{
bool roleExists=等待rolemager.RoleExistsAsync(roleName);
如果(!roleExists)
{
logger.LogInformation(String.Format(“!roleExists for roleName{0}”,roleName));
IdentityRole IdentityRole=新IdentityRole(roleName);
IdentityResult IdentityResult=等待角色管理器.CreateAsync(identityRole);
如果(!identityResult.Successed)
{
logger.LogCritical(
字符串格式(
“!identityResult.successed after”
roleManager.CreateAsync(identityRole)用于
带有roleName{0}的identityRole“,
罗莱奈);
foreach(identityResult.Errors中的var错误)
{
logger.LogCritical(
字符串格式(
“identityResult.Error.Description:{0}”,
错误描述);
logger.LogCritical(
字符串格式(
“identityResult.Error.Code:{0}”,
错误代码);
}
}
}
}
}

我假设您也在等待AddToRoleAsync调用?AddToRoleAsync调用的结果是什么?
    ...

    // Add cookie-based authentication to the request pipeline.
    app.UseIdentity();

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
    // Ensure roles are in DB - OK not to await this for now
    EnsureRoles(app, loggerFactory);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

    ...
private async Task EnsureRoles(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    ILogger logger = loggerFactory.CreateLogger<Startup>();
    RoleManager<IdentityRole> roleManager = app.ApplicationServices.GetService<RoleManager<IdentityRole>>();

    string[] roleNames = { "TheRole", "AnotherRole" };

    foreach (string roleName in roleNames)
    {
        bool roleExists = await roleManager.RoleExistsAsync(roleName);
        if (!roleExists)
        {
            logger.LogInformation(String.Format("!roleExists for roleName {0}", roleName));
            IdentityRole identityRole = new IdentityRole(roleName);
            IdentityResult identityResult = await roleManager.CreateAsync(identityRole);
            if (!identityResult.Succeeded)
            {
                logger.LogCritical(
                    String.Format(
                        "!identityResult.Succeeded after 
                         roleManager.CreateAsync(identityRole) for 
                         identityRole with roleName {0}",
                        roleName));
                foreach (var error in identityResult.Errors)
                {
                    logger.LogCritical(
                        String.Format(
                            "identityResult.Error.Description: {0}", 
                            error.Description));
                    logger.LogCritical(
                        String.Format(
                            "identityResult.Error.Code: {0}", 
                         error.Code));
                }
            }
        }
    }
}