【问题标题】:userManager.FindByName does not return rolesuserManager.FindByName 不返回角色
【发布时间】:2017-07-01 03:31:50
【问题描述】:

我正在使用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

【问题讨论】:

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


    【解决方案1】:

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

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

    在底层,默认的 ASP.NET Core Identity 存储实现(基于 EF)出于性能原因不会急切地加载与用户实体关联的导航属性,这就是未填充 Roles 属性的原因。

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

    【讨论】:

    • 为什么我不能只输入 .Include(Claims) 等并实际得到它哇
    • 我不认为侮辱是表达你的观点的必要条件。如果你想使用Include扩展,你必须创建自己的存储(可以从官方的EF存储中派生)并覆盖返回用户实例的方法。
    • 这只是完全糟糕的创建。您以某种方式检索了一半的财产——另一半。谁认为这个主意很好!?表现?当你让一半的开发社区患上癌症时,你将不会有表现
    • 另一方面,每次检索用户时加载所有导航属性也会对性能产生影响,尤其是当您不需要它们时。
    猜你喜欢
    • 2016-07-12
    • 2021-08-11
    • 2021-10-06
    • 2014-12-25
    • 2013-05-16
    • 2021-04-16
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多