【发布时间】: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