【问题标题】:component.ts class gives an error when the return type is iActionResult当返回类型为 iActionResult 时,component.ts 类给出错误
【发布时间】:2019-02-16 10:21:11
【问题描述】:

我现在有点困惑。每当我从控制器类返回 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"
);

上面的代码示例按预期工作并返回Record Uploaded Successfully

但每当我将 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

【问题讨论】:

  • 你能在网络标签中查看响应状态吗?
  • 在两个实例中返回 200 状态码,当它的 void 和 IActionResult 时。检查图像。

标签: c# angular typescript asp.net-web-api .net-core


【解决方案1】:

从你的 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!"});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    相关资源
    最近更新 更多