【问题标题】:Postman issue The JSON value could not be converted to agsamplewebapi.Model.EmployeePostman 问题 JSON 值无法转换为 agsamplewebapi.Model.Employee
【发布时间】:2020-03-30 01:47:37
【问题描述】:

我正在开发 ASP。 NET Core web api 应用程序,它将暴露给 Angular 6

开发 web api Post 请求后,我进入 PostMan 检查 Post 请求,得到错误 "JSON 值无法转换为 agsamplewebapi.Model.Employee.Path: $ | LineNumber: 0 | BytePositionInLine:1。”

型号代码

 public class Employee
  {
    public int Id { get; set; }
    public string Eno { get; set; }
    public string Ename { get; set; }
    public decimal Salary { get; set; }
    public string Gender { get; set; }
    public string Designation { get; set; }
  }

控制器代码

[EnableCors("CorsPolicy")]
  [Route("api/[controller]")]
  [ApiController]
  public class EmployeesController : ControllerBase
  {
    private readonly EmployeeContext _context;

    public EmployeesController(EmployeeContext context)
    {
      _context = context;
    }
    // POST: api/Employees
    [HttpPost]
    public async Task<ActionResult<Employee>> PostEmployee(Employee employee)
    {
      _context.Employee.Add(employee);
      await _context.SaveChangesAsync();

      return CreatedAtAction("GetEmployee", new { id = employee.Id }, employee);
    }

 }

当使用带有https://localhost:44333/api/Employees 的 Postman 和下面列出的带有 Json 选择的正文时,将在 Postman 窗口下显示错误 “JSON 值无法转换为 agsamplewebapi.Model.Employee。路径:$ | LineNumber: 0 | BytePositionInLine:1。”

[
    {    
        "Eno": "112",
        "Ename": "zzz",
        "Salary": 1888.00,
        "Gender": "M",
        "Designation": "gghh"
    }
]

为我提供解决此问题的合适指南

【问题讨论】:

  • 尝试从json中删除[ ]
  • @Sajid 回答正确,将其移至回答问题部分,将关闭问题
  • 我正在添加答案,您也可以在不更改 Json 的情况下更改操作的签名,但我认为您需要一个对象。

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


【解决方案1】:

您有两种解决方案来解决此问题:

1 - 从Json 中删除[],就像我的评论:

{    
   "Eno": "112",
   "Ename": "zzz",
   "Salary": 1888.00,
   "Gender": "M",
   "Designation": "gghh"
}

2 - [] 表示集合,然后您可以更改操作签名,而无需将Json 更改为:

public async Task<ActionResult<Employee>> PostEmployee(IEnumerable<Employee> employee)
{}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-14
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多