身份框架为用户创建一个新密码(没有密码)

Identity Framework create a new password for a user (without a password)

所以,我有这个网站,用户只能由管理员创建。 我这样设置我的 Web API 方法:

/// <summary>
/// Creates a user (with password)
/// </summary>
/// <param name="model">The bound user model</param>
/// <returns></returns>
[HttpPost]
[Route("")]
public async Task<IHttpActionResult> CreateUser(UserBindingModel model)
{

    // If our ModelState is invalid, return a bad request
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    // Get the current userId and date
    var userId = User.Identity.GetUserId();
    var date = DateTime.UtcNow;

    // Assign our binding model to a new model
    var user = new User()
    {
        CompanyId = model.CompanyId,
        UserName = model.Email,
        Email = model.Email,
        FirstName = model.FirstName,
        LastName = model.LastName,
        LastLoginDate = date,
        Telephone = model.Telephone,

        CreatedById = userId,
        ModifiedById = userId,
        DateCreated = date,
        DateModified = date
    };

    // Try to create the user
    var result = await this.UserService.CreateAsync(user);

    // If the creation fails, return the error
    if (!result.Succeeded)
        return GetErrorResult(result);

    // Send the confimation email
    await SendConfirmationEmail(user.Id);

    // Get the location header
    var locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

    // Return the result
    return Created(locationHeader, this.ModelFactory.Create(user));
}

如您所见,创建了没有密码的用户,并向新用户发送了一封确认电子邮件。 我想用这个确认邮件为用户创建密码,所以我设置了这个方法:

/// <summary>
/// Used to confirm the users email address
/// </summary>
/// <param name="userId">The user id of the user to confirm</param>
/// <param name="code">The generated code that was sent to the email address</param>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
[Route("Confirm", Name = "ConfirmEmailRoute")]
public async Task<IHttpActionResult> ConfirmEmail(ConfirmBindingModel model)
{

    // If our userId or code are not supplied
    if (string.IsNullOrWhiteSpace(model.UserId) || string.IsNullOrWhiteSpace(model.Code))
    {

        // Add an error message to the ModelState
        ModelState.AddModelError("", "User Id and Code are required");

        // And return a BadRequest with the attached ModelState
        return BadRequest(ModelState);
    }

    // Set our password
    var result = await this.UserService.ChangePasswordAsync(model.UserId, "", model.Password);

    // If we didn't manage to create a password, return the error
    if (!result.Succeeded)
        return GetErrorResult(result);

    // Confirm our user
    result = await this.UserService.ConfirmEmailAsync(model.UserId, model.Code);

    // If we didn't manage to confirm the user, return the error
    if (!result.Succeeded)
        return GetErrorResult(result);

    // If we reach this point, everything was successful
    return Ok();
}

问题是将空字符串传递给 ChangePasswordAsync 方法,抱怨提供的密码不正确。

有谁知道如何解决我的问题?

public async Task<IHttpActionResult> ConfirmEmail(ConfirmBindingModel model)
{

    // If our userId or code are not supplied
    if (string.IsNullOrWhiteSpace(model.UserId) || string.IsNullOrWhiteSpace(model.Code))
    {

        // Add an error message to the ModelState
        ModelState.AddModelError("", "User Id and Code are required");

        // And return a BadRequest with the attached ModelState
        return BadRequest(ModelState);
    }

    //<--- in your create user method you set not password so this won't work
    // Set our password
    // var result = await this.UserService.ChangePasswordAsync(model.UserId, "", model.Password);

    //<--- instead you need to use AddPasswordAsync ----->
    var result = await this.UserService.AddPasswordAsync(model.UserId, model.Password);

    // If we didn't manage to create a password, return the error
    if (!result.Succeeded)
        return GetErrorResult(result);

    // Confirm our user
    result = await this.UserService.ConfirmEmailAsync(model.UserId, model.Code);

    // If we didn't manage to confirm the user, return the error
    if (!result.Succeeded)
        return GetErrorResult(result);

    // If we reach this point, everything was successful
    return Ok();
}

基本上CreateUser有两个重载,一个有密码,一个没有。如果您创建一个没有密码的用户,那么您需要使用 AddPassword。否则你可以使用 ChangePassword

MSDN Reference