我想将数据(最初是数组)作为 JSON 发送到后端的 MVC Controller 。我正在尝试这个:
my-ng-service.ts
//...
setEmployees(employees) {
var employeesJSON = JSON.stringify(employees);
console.log(employeesJSON); //working
this.http.post('/api/employees', employeesJSON).subscribe();
}
//...
EmployeesController.cs
//...
[Route("api/[controller]")]
[HttpPost]
public void Post(JsonResult data)
{
Console.Write("hallo: " + data); //error see below
}
//...
我不知道如何编写我的 Controller 。有人可以帮助我吗?
当前错误:
System.Argument.Exception: Type 'Microsoft-AspNetCore.Mvc:JsonResult' does not have a default constructor Parameter name: type
谢谢转发!
最佳答案
JsonResult
是一种用于从操作方法输出 JSON 的类型,而不是作为输入参数。
参见ASP.NET Core MVC : How to get raw JSON bound to a string without a type?和 ASP.NET MVC Read Raw JSON Post Data :您可以将参数类型更改为dynamic
或JObject
,也可以手动将请求正文读取为字符串。
但你确实应该重新考虑这一点。创建一个模型,以便您可以将模型绑定(bind)为强类型,只需几秒钟的工作,并且将使您在将来受益匪浅。
关于c# - 从 Angular 前端 POST JSON 到 ASP.NET 后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47408337/