gpt4 book ai didi

c# - 当返回类型为 iActionResult 时,component.ts 类会报错

转载 作者:搜寻专家 更新时间:2023-10-30 21:35:14 26 4
gpt4 key购买 nike

我现在有点迷茫。每当我从 Controller 类返回 void 时,一切正常。

我的 controller.cs 类。

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[HttpPut("[action]")]
public void EditEmployee(Employee employee)
{
if (ModelState.IsValid)
{
_repo.edit(employee);
_repo.Save();
// return Ok($"update was successful for {employee}");
}
// return BadRequest("Something Went Wrong");

}

我的 service.ts 类

 updateEmployee(employee) {
let token = localStorage.getItem("jwt");
return this._http.put('api/Employee/EditEmployee', employee, {
headers: new HttpHeaders({
"Authorization": "Bearer " + token,
"Content-Type": "application/json"
})
})

和我的 component.ts 类

onSubmit(employeeForm: NgForm) {
//console.log(employeeForm.value);
this._employeeService.updateEmployee(employeeForm.value).subscribe(
success => {
this.Message = "Record Uploaded Successfully";
},

err => this.Message = "An error Occurred"
);

上面的代码示例按预期工作并返回记录上传成功

但是每当我将 controller.cs 类中的返回类型更改为 IActionResult 时,

   [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[HttpPut("[action]")]
public IActionResult EditEmployee(Employee employee)
{
if (ModelState.IsValid)
{
_repo.edit(employee);
_repo.Save();
return Ok($"update was successful for {employee}");
}
return BadRequest("Something Went Wrong");
}

它在我的数据库中成功更新了记录,但在我的 component.ts 类中返回了发生错误

this is it on github

我想了解发生了什么以及为什么我会遇到此错误。

Image when controller.cs file returns void

Image when controller.cs file returns IActionResult

最佳答案

从您的 controller.cs 类返回一个 json 对象而不是字符串文字

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[HttpPut("[action]")]
public IActionResult EditEmployee(Employee employee)
{
if (ModelState.IsValid)
{
_repo.edit(employee);
_repo.Save();
return Json(new { Message="Update was successful!"});
}
return BadRequest(new { Message="Something went wrong!"});
}

关于c# - 当返回类型为 iActionResult 时,component.ts 类会报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52283934/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com