userManager.FindByName不返回角色

时间:2017-02-13 07:55:02

标签: asp.net-core asp.net-identity openiddict asp.net-core-identity

我正在使用OpenIddict for token authentication。昨天当我致电userManager.FindByNameAsync(request.Username)时,我获得了角色用户 今天我得到Roles属性count = 0的用户。

我尝试使用await userManager.GetRolesAsync(user);加载角色,并获得计数为3的数组。这意味着用户有角色。

我不知道发生了什么变化,但是如何使用FindByNameAsync函数加载具有角色的用户?

完整代码:

[HttpPost("token"), Produces("application/json")]
public async Task<IActionResult> Exchange(OpenIdConnectRequest request)
{
    Debug.Assert(request.IsTokenRequest(),
        "The OpenIddict binder for ASP.NET Core MVC is not registered. " +
        "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");

    if (request.IsPasswordGrantType())
    {
        var user = await userManager.FindByNameAsync(request.Username);  //roles count is 0
        if (user == null)
        {
            return BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.InvalidGrant,
                ErrorDescription = "The email/password couple is invalid."
            });
        }
        var roles = await userManager.GetRolesAsync(user);  //roles count is 3

1 个答案:

答案 0 :(得分:6)

  

但是如何使用FindByNameAsync函数加载具有角色的用户?

你不能(至少没有实现你自己的IUserStore)。

由于性能原因,默认的ASP.NET核心标识存储实现(基于EF)并不急于加载与用户实体关联的导航属性,这就是Roles属性的原因没有填充。

要加载与用户关联的角色,请使用UserManager.GetRolesAsync(user);