【问题标题】:Handle 400 Bad Request From WebApi In Angular 6 (using HttpClient)在 Angular 6 中处理来自 WebApi 的 400 错误请求(使用 HttpClient)
【发布时间】:2019-04-02 08:38:41
【问题描述】:

下面是一个 Asp.net Core WebAPI,当我们说重复用户尝试注册时,它会返回错误的请求以及关于其参数的错误详细信息。

public async Task<IActionResult> Register([FromBody] RegisterModel registerModel)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
            {
                //TODO: Use Automapper instead 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);
            });

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

邮递员结果:

但尽管尝试了多个代码 sn-p 仍然没有结果,但结果相同,所有它都会记录“错误结果”作为响应。

角度结果:

虽然响应位于网络选项卡中,但我确实注意到了.. 只是缺少处理它的想法。

错误描述:

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

【问题讨论】:

  • 你在邮递员结果中得到什么 HTTP 状态码?
  • 400 错误结果。
  • 我的应用中出现同样的问题,但仍然没有答案...
  • 您找到解决方案了吗?

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


【解决方案1】:

您将在 Angular 应用程序和邮递员中从您的 API 获得 400 个 Http-status 代码:

顺便说一句:400 状态是 API 预期行为。它未能创建用户并发送错误描述以及适当的 HTTP 状态 (400)。如果您想处理此 API 错误,最好的选择是 (referred angular HttpErrorResponse type)

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 errorPayload = JSON.parse(error.message);
                //ToDo: apply your handling logic e.g.:
                //console.log(errorPayload[0].description
                console.log(error.error);
            });

【讨论】:

  • 也参考了它.. 没有状态代码的 Qualms 我对它在 Postman 呈现的错误描述感兴趣。问题,以错误的名义,我在客户端只看到一个文本“错误结果”。仅此而已!
  • 客户端不能有一个代理来拦截错误响应吗?
  • @Jason let errorPayload = JSON.parse(error.message) 这个在调试器中的价值是什么? (error:HttpErrorResponse) =>... 参数对象的状态是什么?请提供此对象的转储
  • @n.piskunov errorPayload = JSON.parse(error.message) 导致“未定义”。 (errr:HttpErrorRrsponse...) 也会发生同样的情况。 github.com/angular/angular/issues/26817 提到了更多的屏幕截图。但是我注意到 Http 而不是 HttpClient 的预期结果(为什么会这样?)。将很快发布更多详细信息。
【解决方案2】:

Dotnet Core 400 Identity 错误响应是一个 {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);
      });
   }
}

更新:这是特定于身份框架的。 (登录和注册)。在其他领域,错误处理将需要手动工作才能与此模式保持一致。

【讨论】:

    【解决方案3】:

    我在 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);
            }
        );
    }
    

    【讨论】:

      【解决方案4】:

      我遇到了同样的错误

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

      只是因为忘记加了

      formData: Employee = new Employee();

      现在它可以在我的 .net 核心 webapi 上运行良好 Click here for code

      【讨论】:

        猜你喜欢
        • 2020-07-10
        • 1970-01-01
        • 1970-01-01
        • 2015-06-02
        • 1970-01-01
        • 1970-01-01
        • 2014-09-22
        • 2022-11-23
        • 1970-01-01
        相关资源
        最近更新 更多