AspNet.Identity CreateAsync不会返回user.Id与CustomStore

时间:2016-11-02 17:04:58

标签: c# asp.net-identity

我已经搜遍了所有内容,我认为我的代码中存在错误/缺失。

我已经编写了一个自定义UserStore来处理AspNet Identity。我的CreateAsync代码如下所示:

public Task CreateAsync(ApplicationUser user)
{
    var newUser = _permissionApiClient.Store(Mapper.Map<AccountDomainModel>(user));
    // newUser does have the Id

    // I would think I return newUser, but samples say to return null?
    return Task.FromResult<Object>(null);
}

当我的AccountController.Register触发时,它会创建帐户,但是当我需要user.Id时(当我尝试获取确认码时),它没有填充。

public async Task<ActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, FirstName = model.FirstName, LastName = model.LastName};
        var result = await UserManager.CreateAsync(user, model.Password);
        // At this point, the record is in the database with an id.
        if (result.Succeeded)
        {
            await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

            // user.Id here is 0 (zero). I do get a SignIn token/cookie tho
            string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            // ...
            return RedirectToAction("Index", "Home");
        }
        AddErrors(result);
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}

我不确定我错过了什么。 UserManager.CreateAsyncSignInManager.SignInAsync是否应该进行ByRef来电?我需要手动做某事吗?

这是我的一些代码:

public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
    public ApplicationUserManager(IUserStore<ApplicationUser, int> store, IDataProtectionProvider dataProtectionProvider)
        : base(store)
    {
        // Configure validation logic for usernames
        UserValidator = new UserValidator<ApplicationUser, int>(this)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        // Configure user lockout defaults
        UserLockoutEnabledByDefault = false;

        //// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        //// You can write your own provider and plug it in here.
        EmailService = new EmailService();
        SmsService = new SmsService();

        if (dataProtectionProvider != null)
        {
            UserTokenProvider = 
                new DataProtectorTokenProvider<ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
    }
}

我的AppliationUser:

public class ApplicationUser : IUser<int>
{
    public int Id { get; set; }
    public string UserName { get; set; }


    public string FirstName { get; set; }
    public string LastName { get; set; }

    /// <summary>
    ///     The salted/hashed form of the user password
    /// </summary>
    public virtual string PasswordHash { get; set; }
    public bool IsEmailConfirmed { get; set; }

    /// <summary>
    ///     Is two factor enabled for the user
    /// </summary>
    public virtual bool TwoFactorEnabled => false;

    /// <summary>
    ///     Is lockout enabled for this user
    /// </summary>
    public virtual bool LockoutEnabled => false;

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> 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;
    }
}

1 个答案:

答案 0 :(得分:0)

我必须将Id推送到user对象。

public Task CreateAsync(ApplicationUser user)
{
    if (user == null)
    {
        throw new ArgumentNullException(nameof(user));
    }

    var newUser = _permissionApiClient.Store(Mapper.Map<AccountDomainModel>(user)).Result;
    user.Id = newUser.AccountId;

    return Task.FromResult<Object>(null);
    //return thisUser;
}