在Angular 6中处理来自WebApi的400错误请求(使用HttpClient)

时间:2018-10-29 12:01:24

标签: angular asp.net-web-api asp.net-core jwt access-token

下面是一个Asp.net Core WebAPI,当假设有重复的用户尝试注册时,该错误返回带有错误详细信息作为参数的错误请求。

public async Task<IActionResult> Register([FromBody] RegisterModel registerModel)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
            {
                //TODO: Use Automapper instaed of manual binding  

                UserName = registerModel.Username,
                FirstName = registerModel.FirstName,
                LastName = registerModel.LastName,
                Email = registerModel.Email
            };
            var identityResult = await this.userManager.CreateAsync(user, registerModel.Password);
            if (identityResult.Succeeded)
            {
                await signInManager.SignInAsync(user, isPersistent: false);
                return Ok(GetToken(user));
            }
            else
            {
                Console.WriteLine("Errors are : "+ identityResult.Errors);
                return BadRequest(identityResult.Errors);
            }
        }
        return BadRequest(ModelState);

正在Angular端处理响应,如下所示:

user.service.ts

register(user: User) {
   // let headers = new Headers({ 'Content-Type': 'application/json' });
   //var reqHeader = new HttpHeaders({ 'Content-Type': 'application/json'});
   const reqHeader = new HttpHeaders().set('Content-Type', 'application/json')
                            .set('Accept', 'application/json');
//return this.http.post(this.rootUrl + '/api/account/register', body,{headers : reqHeader});

    return this.http.post(this.apiUrl+ '/api/account/register', user,{headers : reqHeader});
}

以上方法被调用:

register.component.ts

this.userService.register(this.registerForm.value)
        .pipe(map((res: Response) => res.json()))
        .subscribe(
            data => {
                this.alertService.success('Registration successful', true);
                this.router.navigate(['/login']);
            },
            (error:HttpErrorResponse) => {
                // let validationErrorDictionary = JSON.parse(error.text());
                // for (var fieldName in validationErrorDictionary) {
                //     if (validationErrorDictionary.hasOwnProperty(fieldName)) {
                //         this.errors.push(validationErrorDictionary[fieldName]);
                //     }
                // }
                // this.alertService.errorMsg(this.errors);
                console.log(error.error);
            });

当我尝试做邮递员时,我得到了如下完美的结果:

PostmanResult

但是,尽管尝试了多个代码段,但仍无法得到相同的结果,并且所有结果都记录为“不良结果”作为响应。

AngularResult

我确实注意到,尽管响应位于“网络”标签中。但是缺少处理它的想法。

ErrorDescription

这里缺少什么?非常感谢您的回复!

5 个答案:

答案 0 :(得分:5)

我在angular 7中也遇到了同样的问题。但是我今天使用以下代码解决了这个问题:

在使用中:

registerUser(userdata): Observable<any> {
    return this.httpClient.post('url', userdata).pipe(catchError(this.handleError));
}

handleError(error: HttpErrorResponse) {
    return throwError(error);
}

在register.component.ts中:

postData() {
    this.auth.registerUser(userdata).subscribe(
        (resp) => {
            console.log(resp);
        },
        (error) => {
            console.log(error.error);
        }
    );
}

答案 1 :(得分:0)

您将在Angle App和邮递员的API中获得400个Http状态代码:enter image description here

BTW :400状态是API预期的行为。它无法创建用户并发送错误说明以及适当的HTTP状态(400)。如果要处理此API错误,最好的选择是类似(称为成角的HttpErrorResponse类型)

compile project(':react-native-gps')
compile project(':react-native-maps')

答案 2 :(得分:0)

Dotnet Core 400身份错误响应是{code,description}的数组。 因此,要在打字稿中处理它,首先要定义一个接口(实际上不是必需的,但要进行严格的类型检查。

interface ClientError {
    code: string;
    description: string;
}

然后在您处理错误的部分中,执行以下操作

(error:HttpErrorResponse) => { 
   if(error.status===400){            
      const errors: Array<ClientError> = error.error;
      errors.forEach(clientError => {
         console.log(clientError.code);
      });
   }
}

更新:这特定于Identity Framework。 (登录和注册)。在其他方面,错误处理将需要手动工作才能与该模式保持一致。

答案 3 :(得分:0)

在我的情况下,邮递员打电话给return如下:

enter image description here

在我的情况下,返回角如下:

enter image description here

您可以访问以下网址错误消息:

https://stackblitz.com/edit/angular-kmgxuo

以您的情况为例,它将返回Array,以便您可以像 error[0].code

那样访问

答案 4 :(得分:-2)

我遇到了同样的错误

<块引用>

消息:“https://localhost:44397/api/AddEmployee 的 HTTP 失败响应:400 OK” 名称:“HttpErrorResponse” 确定:假 状态:400 状态文本:“好的” url: "https://localhost:44397/api/AddEmployee"

只是因为我忘了添加

<块引用>

formData: Employee = new Employee();

现在我的 .net core webapi 可以正常运行了 Click here for code