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
Employeeto a collection type likeList<Employee>(orIEnumerable<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
whileloop, rather than replacing theempvariable 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
相关产品推荐
相关产品推荐

