【问题标题】:Angular- Always geting a 400 Bad Request responseAngular-总是收到 400 Bad Request 响应
【发布时间】:2021-03-27 12:53:51
【问题描述】:

我正在尝试将前端连接到后端的端点,但总是收到 400:Bad Request 响应,我不知道为什么。我已经在 Swagger 中使用相同的电子邮件值测试了我的端点,它工作得非常好。我还可以确认我收到的电子邮件是有效的,并且它的类型是字符串。为什么我的连接没有建立?

前端

 resetPassword(email: String): Observable<any> {
    console.log("Type:" ,typeof(email));
    console.log("THE RECEIVED EMAIL IS: ", email);
    return this.http.post<any>(
      endpoint + 'User/ForgetPassword',
      JSON.stringify(email),
      httpOptions
    );
  }

后端

  [AllowAnonymous]
        [HttpPost("ForgetPassword")]
        public IActionResult ForgetPassword([FromBody]ForgetCredencialModel model)
        {
            try
            {
                var newPassword = _userService.GenerateRandomPassword();
                var user = _userService.UpdateCredentials(model.Email, newPassword);
                _emailService.ForgetCredencialsEmail(user.Username, newPassword, model.Email);

                return Ok(new { Message = "New Password in the email !" });
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        }

型号

  public class ForgetCredencialModel
    {
        public string Email { get; set; }
    }

【问题讨论】:

  • 请同时显示ForgetCredencialModel 型号
  • @RomanMarusyk 完成
  • 您是否尝试过使用调试器查看是哪一项服务引发了错误。您收到的 BadRequest 异常消息是什么?您也可以尝试使用ex.ToString() 来获取错误的完整图片(而不仅仅是ex.Message
  • @Jawad 这是我收到的错误code error: {…} ​​ errors: Object { "$": (1) […] } ​​ status: 400 ​​ title: "One or more validation errors occurred." ​​ traceId: "|3e98b69b-4efbe766cfc8b860." ​​ type: "https://tools.ietf.org/html/rfc7231#section-6.5.1" ​​ &lt;prototype&gt;: Object { … } ​ headers: Object { normalizedNames: Map(0), lazyUpdate: null, lazyInit: lazyInit() } ​ message: "Http failure response for http://localhost:5000/User/ForgetPassword: 400 Bad Request"

标签: c# angular rest .net-core


【解决方案1】:

应该是

JSON.stringify({Email: email}));

因为你的动作需要一个身体

{ "Email": "your@email" }

如果您不打算使用其他属性扩展ForgetCredencialModel,则将其简化并使用JSON.stringify(email)

public IActionResult ForgetPassword([FromBody]string email)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 2012-01-12
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多