You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET WebAPI如何向Angular返回JSON格式的数组对象

Fix to Return JSON Array from Your ASP.NET Web API

Hey there! I see the issue here—your current method returns a single Employee object, which is why you're getting a single JSON object instead of an array. Let's adjust this to return a collection so it serializes to the JSON array format you need.

Here's what you need to do:

  • Change the return type from Employee to a collection type like List<Employee> (or IEnumerable<Employee> if you prefer)
  • Initialize a list to store all your employee records instead of overwriting a single variable
  • Add each employee to the list inside your while loop, rather than replacing the emp variable each time
  • Return the list instead of the single object

Here's the updated code:

[HttpGet]
[ActionName("GetEmployeeByID")]
public List<Employee> Get(int id)
{
    var employees = new List<Employee>();
    while (reader.Read())
    {
        var emp = new Employee();
        emp.ClientId = Convert.ToInt32(reader.GetValue(0));
        emp.ClientName = reader.GetValue(1).ToString();
        employees.Add(emp);
    }
    return employees;
}

Once you make this change, your API will return a JSON array like [{"ClientId":15,"ClientName":"Abhinav Singh"}]—even if there's only one matching record, it'll be wrapped in an array just like you want. If you ever have multiple employee records matching the ID, they'll all be included in the array too.

内容的提问来源于stack exchange,提问作者Amol Naik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:41:36