typescript 使用Angular更新ASP.NET Core 6中用户的密码

gab6jxml  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(133)

我想更新API的用户密码,它工作良好,但不是从UIAngular 工作;在这个项目中,我使用了ASP.NET核心6 Web API和Angular 13。
ASP.NET核心Web API的代码:

[HttpPut]
[Route("Change-password")]
public async Task<IActionResult> ChangePassword([FromBody] ChangePassword model)
{
    var user = await userManager.FindByEmailAsync(model.Email);

    if (user == null)
    {
        return StatusCode(StatusCodes.Status404NotFound, new Response { Status = "Error", Message = "User does not exist" });
    }

    if (string.Compare(model.NewPassword, model.ConfirmNewPassword) != 0)
    {
        return StatusCode(StatusCodes.Status404NotFound, new Response { Status = "Error", Message = "The new password and confirm new password do not match" });
    }

    var result = await userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword);

    if (result.Succeeded)
    {
       var errors = new List<string>();

       foreach (var error in result.Errors)
       {
           errors.Add(error.Description);
       }
                
       return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Success", Message = "Password changed successfully" });
     }

     return Ok(new Response { Status = "Error", Message = "Current password is incorrect" });
}

HTML标记:

<form #passwordUpdateForm="ngForm" (ngSubmit)="updatePassword(passwordUpdateForm)" class="col-md-4 mt-3">
    <div *ngIf="!!password_update_msg" [ngClass]="has_error ? 'alert alert-danger': 'alert alert-info'">{{password_update_msg}}</div>
    <div class="row">
        <mat-form-field class="col-sm-12">
            <input matInput name="oldPassword" ngModel placeholder="Old Password" [type]="ohide ? 'password' : 'text'" required>
                <mat-icon matSuffix (click)="ohide = !ohide">{{ohide ? 'visibility_off' : 'visibility'}}</mat-icon>
         </mat-form-field>
     </div>

     <div class="row">
         <mat-form-field class="col-sm-12">
             <input matInput name="newPassword" ngModel placeholder="New Password" [type]="nhide ? 'password' : 'text'" required>
             <mat-icon matSuffix (click)="nhide = !nhide">{{nhide ? 'visibility_off' : 'visibility'}}</mat-icon>
         </mat-form-field>
     </div>

     <div class="row">
         <mat-form-field class="col-sm-12">
             <input matInput name="reNewPassword" ngModel placeholder="Confirm New Password" [type]="rnhide ? 'password' : 'text'" required validateEqual="newPassword" #reNewPassword="ngModel">
             <mat-icon matSuffix (click)="rnhide = !rnhide">{{rnhide ? 'visibility_off' : 'visibility'}}</mat-icon>
         </mat-form-field>
     </div>

     <button class="mt-4 btn-block" type="submit" mat-raised-button color="primary" [disabled]="passwordUpdateForm.invalid">Change Password</button>
</form>

Service.ts代码:

UpdatePassword(oldPassword:string,newPassword:string): Observable<any>{
const body= new FormData();
body.append('oldPassword',oldPassword);
body.append('newPassword', newPassword);
return this.http.put<any>(this.baseUrl+'/Change-password', body )
     .pipe(catchError(this.errorHandler));
    }

代码T

updatePassword(form: any) {
    const oldPassword = form.value.oldPassword;
    const newPassword = form.value.newPassword;
    const reNewPassword = form.value.reNewPassword;

    if (newPassword !== reNewPassword) {
      this.has_error = true;
      this.password_update_msg = 'New Password and Confirm Password must be same';
      return;
    }

    this.userService.UpdatePassword(oldPassword, newPassword)
      .subscribe(() => {
        this.has_error = false;
        this.password_update_msg = 'Password Update Successful, Please Logout and Re Login !!!';
        form.reset();
      },
        () => {
          this.has_error = true;
          this.password_update_msg = 'Password Update Failed !!!';
        });
  }

当我将数据从Angular发送到API时,我收到一个错误:
不支持的媒体类型415
有人能帮帮我吗?

yruzcnhs

yruzcnhs1#

解决方案1:将对象作为请求正文传递

由于您的ChangePassword API使用[FromBody]属性:

public async Task<IActionResult> ChangePassword([FromBody] ChangePassword model)

在前端,您使用传递对象作为请求主体,如下所示:

UpdatePassword(oldPassword:string,newPassword:string): Observable<any>{
  let body = {
    oldPassword: oldPassword,
    newPassword: newPassword
  };

  return this.http.put<any>(this.baseUrl+'/Change-password', body )
     .pipe(catchError(this.errorHandler));
}

解决方案2:将对象作为表单数据传递

否则,请套用[FromForm]属性,而非ChangePassword API中的[FormBody]属性。

public async Task<IActionResult> ChangePassword([FromForm] ChangePassword model)

相关问题