繁体   English   中英

UserManager.AddToRole将空用户ID传递给FindByIdAsync

[英]UserManager.AddToRole passes null user id to FindByIdAsync

我有一个MVC网站,该网站在我自己的表中使用自定义身份。 大多数情况下一切正常……添加用户,角色等。

现在,我通过用户管理器将用户添加到角色中,如下所示:

var result = um.AddToRole(userID, roleName);

“ um”是我的UserStore界面。 在调用AddToRole方法之前,它将调用FindByIdAsync方法,并为用户ID传递一个空值。 不好。 这破坏了整个过程。

Microsoft Identity决定如何在后台调用这些例程,但我不知道为什么会传递null。 我猜我在UserStore实现中有问题,但是我找不到它。

当我尝试AddToRole时,什么叫FindByIdAsync方法?

AddToRole方法是一种扩展方法,定义为:

/// <summary>
/// Add a user to a role
/// 
/// </summary>
/// <param name="manager"/><param name="userId"/><param name="role"/>
/// <returns/>
public static IdentityResult AddToRole<TUser, TKey>(this UserManager<TUser, TKey> manager, TKey userId, string role) where TUser : class, IUser<TKey> where TKey : IEquatable<TKey>
{
  if (manager == null)
    throw new ArgumentNullException("manager");
  return AsyncHelper.RunSync<IdentityResult>((Func<Task<IdentityResult>>) (() => manager.AddToRoleAsync(userId, role)));
}

UserManagerExtensions 如您所见,它只是调用AddToRoleAsync ,而后者又定义为:

 /// <summary>
    /// Add a user to a role
    /// 
    /// </summary>
    /// <param name="userId"/><param name="role"/>
    /// <returns/>
    public virtual async Task<IdentityResult> AddToRoleAsync(TKey userId, string role)
    {
      this.ThrowIfDisposed();
      IUserRoleStore<TUser, TKey> userRoleStore = this.GetUserRoleStore();
      TUser user = await TaskExtensions.WithCurrentCulture<TUser>(this.FindByIdAsync(userId));
      if ((object) user == null)
        throw new InvalidOperationException(string.Format((IFormatProvider) CultureInfo.CurrentCulture, Resources.UserIdNotFound, new object[1]
        {
          (object) userId
        }));
      IList<string> userRoles = await TaskExtensions.WithCurrentCulture<IList<string>>(userRoleStore.GetRolesAsync(user));
      IdentityResult identityResult;
      if (userRoles.Contains(role))
      {
        identityResult = new IdentityResult(new string[1]
        {
          Resources.UserAlreadyInRole
        });
      }
      else
      {
        await TaskExtensions.WithCurrentCulture(userRoleStore.AddToRoleAsync(user, role));
        identityResult = await TaskExtensions.WithCurrentCulture<IdentityResult>(this.UpdateAsync(user));
      }
      return identityResult;
    }

UserManager 因此,如果此调用:

TUser user = await TaskExtensions.WithCurrentCulture<TUser>(this.FindByIdAsync(userId));

为userID传递null,然后通过查看调用链,只能是因为您要为userID传递null值。

因此,回答您的问题:

当我尝试AddToRole时,什么叫FindByIdAsync方法?

A: UserManager.AddToRoleAsync

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM