You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC登录失败后,如何在Angular客户端捕获展示JSON错误信息?

Angular 9登录页展示ASP.NET Core MVC返回的具体登录错误信息

问题背景

之前ASP.NET Core MVC服务器返回400 Bad Request时,Angular 9客户端只能显示通用错误提示,无法向用户展示诸如「用户不存在」「密码无效」这类具体的登录失败原因。

解决方案思路

调整服务器返回逻辑:不再返回400状态码,改用203 Non-Authoritative Information状态码,并返回包含LoginError字段的JSON响应体;同时修改Angular客户端的数据源层、认证服务及登录组件,实现错误信息的捕获、传递与页面展示。


1. 服务器端调整(ASP.NET Core MVC)

修改登录接口的返回逻辑,当登录验证失败时,返回203状态码及错误信息JSON:

// 示例:AccountController中的Login方法
[HttpPost]
public IActionResult Login(LoginViewModel model)
{
    if (!ModelState.IsValid)
    {
        // 验证失败时返回203及具体错误
        return StatusCode(203, new { LoginError = "用户名或密码错误" });
    }
    // 登录成功逻辑...
    return Ok();
}

2. Angular客户端修改

数据源层(AuthDataService)

修改HTTP请求的错误处理逻辑,捕获203状态码的响应,提取其中的LoginError信息:

// auth-data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class AuthDataService {
  constructor(private http: HttpClient) { }

  login(credentials: { username: string; password: string }) {
    return this.http.post('/api/account/login', credentials)
      .pipe(
        catchError((error: HttpErrorResponse) => {
          if (error.status === 203) {
            // 提取服务器返回的具体错误信息
            return throwError(() => error.error.LoginError);
          }
          // 其他错误返回通用提示
          return throwError(() => '登录失败,请稍后重试');
        })
      );
  }
}

认证服务(AuthService)

调用数据源层的登录方法,将错误信息传递给组件:

// auth.service.ts
import { Injectable } from '@angular/core';
import { AuthDataService } from './auth-data.service';

@Injectable({ providedIn: 'root' })
export class AuthService {
  constructor(private authDataService: AuthDataService) { }

  login(credentials: { username: string; password: string }) {
    return this.authDataService.login(credentials);
  }
}

登录组件(LoginComponent)

在组件中处理登录请求,接收错误信息并绑定到模板:

// login.component.ts
import { Component } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent {
  credentials = { username: '', password: '' };
  loginError: string | null = null;

  constructor(private authService: AuthService) { }

  onSubmit() {
    this.loginError = null;
    this.authService.login(this.credentials)
      .subscribe({
        next: () => {
          // 登录成功后的跳转逻辑
        },
        error: (err) => {
          this.loginError = err;
        }
      });
  }
}

在模板中用<h4>元素展示具体错误:

<!-- login.component.html -->
<form (ngSubmit)="onSubmit()">
  <div class="form-group">
    <label>用户名</label>
    <input type="text" [(ngModel)]="credentials.username" name="username" required>
  </div>
  <div class="form-group">
    <label>密码</label>
    <input type="password" [(ngModel)]="credentials.password" name="password" required>
  </div>
  <button type="submit">登录</button>
  <!-- 展示具体错误信息 -->
  <h4 *ngIf="loginError" class="text-danger">{{ loginError }}</h4>
</form>

内容的提问来源于stack exchange,提问作者Cwinds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 10:35:03