【问题标题】:Cant get data in model from frontend to backendASP web API Angular无法从前端到后端 ASP Web API Angular 获取模型中的数据
【发布时间】:2022-11-17 18:36:20
【问题描述】:

我试图从角度前端登录到 ASP.net API 后端,但是当我尝试在请求中为数据模型提供电子邮件和密码时,它不会到达后端,而命名完全相同。

这是我在 ASP 中的端点:

[Route("/[controller]/Login")]
        [HttpPost]

    public async Task<IActionResult> Login(LoginForm loginForm)

这是我在 ASP 中的班级登录表单:

public class LoginForm
    {
        [Required]
        public string Email { get; set; }
        [Required]
        public string Password { get; set; }

    }

这是我在 Angular 中的请求代码:

login(model: LoginForm) {

    console.log(model);

    return this.http.post(this.authUrl + "Login" , model, {}).pipe(
      map((response: any) => {
        const user = response;


        if (user.result.accountID > 0) {
          localStorage.setItem("token", user.token);
          this.decodedToken = this.helper.decodeToken(user.token);
        }
      })
    );
  }

这是我在 Angular 中的 LoginForm 类:

export interface LoginForm {
    Email: string;
    Password: string;
}

这是我尝试时的控制台日志:

{Email: 'test', Password: 'test'}

这是我尝试时来自网络的请求负载:

{Email: "test", Password: "test"}
Email
: 
"test"
Password
: 
"test"

我该如何解决这个问题?

【问题讨论】:

    标签: asp.net angular api model request


    【解决方案1】:

    我不知道 ASP 是如何工作的,但我知道 Angular。

    当你用 Angular 调用 Backend 时,你需要订阅 observable 来获取数据。

    
        this.http.get<any>(this.apiURL + "/Login").subscribe(response => {
            console.log(response);
        })
    

    如果你想处理一些错误,你可以这样做。

    this.http.get<any>(this.apiURL + "/Login").subscribe(response => {
            console.log(response);
        },
        (error) => {
            console.error(error);
            switch(error.status){
                case 404:
                    // 404 code
                    break;
                case 500:
                    // 500 code
                    break;
                default : 
                    break
            }
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 2022-01-25
      • 2019-05-27
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多