我现在有点困惑。每当我从控制器类返回void时,一切都很好。
我的控制器.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");

    }

我的服务班
 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"
);

上面的代码示例按预期工作,并返回已成功上载的记录
但是每当我将MealCurr.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

最佳答案

从控件.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!"});
}

07-26 01:22