我正在开发一个前端使用 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;
}
可能出了什么问题?