0

我正在开发一个前端使用 Angular 12 和 API 中使用 ASP.net core 5 的应用程序。调用 HttpPost API 时出现错误加载资源失败:服务器响应状态为 400 ()

如果我使用字符串或整数参数,则没有问题,并且 API 被正确调用。但只有当我使用实体类传递值时,我才会收到此错误。

这是我在 asp.net 核心中的实体类

public class FrontEnd
{ 
  public class SendOTPReq
    {
        public string MobileNo { get; set; }
        public string Email { get; set; }
        public int Type { get; set; }
    }
}

这是API

    [Route("SendOTP")]
    [HttpPost]
    public async Task<object> SendOTP(SendOTPReq otpReq)
    {
        try
        {
            CommonApiResponse commonResponse = new CommonApiResponse();

            if (!ModelState.IsValid)
            {
                return new APIResponse(406, "", ModelState.Select(t => new { t.Key, t.Value.Errors[0].ErrorMessage }));
            }
            var Result = await _IFrontEndRepository.SendOTP(otpReq);
            if (Result != null)
            {
                commonResponse.Status = "Success";
                commonResponse.ErrorMsg = "";
                commonResponse.ResultData = Result;
                return new APIResponse(200, "Request Success", commonResponse);
            }
            else
            {
                commonResponse.Status = "Failed";
                commonResponse.ErrorMsg = Result.Message;
                commonResponse.ResultData = Result;
                return new APIResponse(204, "Request Failed", commonResponse);
            }
        }
        catch (Exception e)
        {

            throw new Exception(e.Message);
        }

    }

这是我的角度 component.ts 代码:

const otpReq = new SendOTPReq();

otpReq.MobileNo = this.registerForm.controls['phoneNo'].value;
otpReq.Email = this.registerForm.controls['email'].value;
otpReq.Type = 2; //2 is or email and 1 is for sms

this.accountsService.sendOTP(otpReq).subscribe(      
  (data) => {
         //do stuff here
    
         });

角服务方法:

export class AccountsService {

constructor(private httpClient: HttpClient,
private _router: Router) { }

 sendOTP(otpReq: SendOTPReq): Observable<SendOTPReq> {
  debugger;
  return this.httpClient.post<SendOTPReq>(environment.ApiUrl + 'FrontEnd/SendOTP', otpReq)
    .pipe(
      catchError(this.errorHandler),
    );
}


errorHandler(error: { error: { message: string; }; status: undefined; message: any; }) {
  debugger;
  let errorMessage = '';
  if (error.error instanceof ErrorEvent) {
    // Get client-side error
    errorMessage = error.error.message;
  } else {
    // Get server-side error
    if(error.status == undefined)
    {
      errorMessage = "The server connection with the application is showing error. Close the application and restart again."
    }else{
    errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
  }      
  return throwError(errorMessage);
}

}

角模型类:

export class SendOTPReq
{
  MobileNo!:string;
  Email!: string;
  Type!: number;
}

可能出了什么问题?

4

3 回答 3

1

您的 POST 请求的返回类型错误。object当您的 Angular httpClient 要求返回时,您不能让控制器SendOTPReq返回。

所以你需要

return this.httpClient.post<MyActualReturnType>(environment.ApiUrl + 'FrontEnd/SendOTP', otpReq)
于 2021-06-21T11:33:23.043 回答
1

尝试在您的 API 中添加一个 [FromBody] 装饰器,如下所示:

public async Task<object> SendOTP([FromBody]SendOTPReq otpReq)

更新:根据对此和其他答案的评论,似乎设置一些错误处理以及在您的 POST 请求中更加冗长可能会更清楚地了解导致问题的原因。假设你[FromBody]的 API 中有我上面描述的装饰器,让我们进一步增强专注于返回类型的 API,以及使用 RxJs 的 Angular 中的服务函数,看看我们是否能以某种方式从中提取更有用的响应。

为了清晰和总结,取消嵌套您的 SendOtpReq 类:

public class SendOTPReq
{
    public string MobileNo { get; set; }
    public string Email { get; set; }
    public int Type { get; set; }
}

接下来,让我们将控制器 POST 方法的返回类型调整为 IActionResult:

[Route("SendOTP")]
[HttpPost]
public async Task<IActionResult> SendOTP([FromBody]SendOTPReq otpReq)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    try
    {                
        var Result = await _IFrontEndRepository.SendOTP(otpReq);
        if (Result != null)
        {
            return Ok(Result);                       
        }

        return BadRequest($"Fail to POST");    
     }
     catch (Exception ex)
     {    
         return BadRequest($"Fail to POST");
     }

 }

现在,让我们使用您的角度服务来观察 API 的整个响应,而不仅仅是正文:

public sendOTP(otpReq: SendOTPReq): Observable<HttpResponse<SendOTPReq>> {
  return this.httpClient.post<SendOTPReq>(environment.ApiUrl +
             'FrontEnd/SendOTP', otpReq { observe: "response" })
             .pipe(
             catchError(this.errorHandler),
    );
}
于 2021-06-21T18:41:52.580 回答
1

所以,最后,我修复了它。评论属性和取消评论一个接一个。当我从“mobileNo”字段中获取数据时,我没有将其转换为字符串。将手机号码转换为字符串有效。

我改变了这一行:

otpReq.MobileNo = this.registerForm.controls['phoneNo'].value;

otpReq.MobileNo = this.registerForm.controls['phoneNo'].value.toString();
于 2021-06-22T15:09:47.323 回答