【问题标题】:How to add extra information to IdentityUser and extend UserManager methods如何向 IdentityUser 添加额外信息并扩展 UserManager 方法
【发布时间】:2018-11-11 17:55:06
【问题描述】:

我正在使用 Asp.net mvc IdentityUser 类将用户存储在我的应用程序中。在数据库中有 AspNetUsers 表,所有用户都没有电子邮件。但现在我需要向 ApplicationUser 类添加额外的客户信息。现在,拥有电子邮件的用户可以同时为客户 A 和客户 B 使用相同的电子邮件。

我的 ApplicationUser 类是这样的:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    public Customer Customer { get; set; }
    [Required]
    public int CustomerId { get; set; }
}

但我找不到扩展 UserManager 并根据需要更改方法的方法。

public async System.Threading.Tasks.Task<bool> AddAccount(string email, int customerId)
{
    // Asp.net User
    var user = await UserManager.FindByEmailAsync(email);
    string password = Membership.GeneratePassword(5, 1);
    if (user == null)
    {
        user = new ApplicationUser { UserName = email, Email = email, CustomerId = customerId };
        var result = await UserManager.CreateAsync(user, password);
        if (!result.Succeeded)
        {
            return false;
        }
    }

    return true;
}

我需要扩展 FindByEmailAsync 方法,它不仅接受 email 参数,还接受 CustomerId 作为参数。

我需要 FindByEmail(string email, int customerId) 但我不知道该怎么做?

【问题讨论】:

  • 为什么不能覆盖这个方法
  • @erdiyılmaz 如果您覆盖该方法必须具有相同的输入参数

标签: c# asp.net asp.net-mvc asp.net-identity


【解决方案1】:

如果您想这样做,您必须创建继承自 UserManagerMyUserManager。然后添加方法FindByEmailAndId([your params])

像这样:

public class MyUserManager<TUser> : UserManager<TUser>
{
    public async Task<TUser> FindByEmailAsync(string email, int customerId)
    {
        //your code.
    }
}

但我不明白为什么?如果你创建一个用户,你的一两个参数必须是 unic。那为什么不用这个参数呢?

【讨论】:

    猜你喜欢
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2019-11-10
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多