I want to create WEB API which sends input to Angular. I want to send data in JSON format as an array.
Below is my code:
[HttpGet]
[ActionName("GetEmployeeByID")]
public Employee Get(int id)
{
Employee emp = null;
while (reader.Read())
{
emp = new Employee();
emp.ClientId = Convert.ToInt32(reader.GetValue(0));
emp.ClientName = reader.GetValue(1).ToString();
}
return emp;
}
Actual output:
{"ClientId":15,"ClientName":"Abhinav Singh"}
Expected output:
[{"ClientId":15,"ClientName":"Abhinav Singh"}]
Yurii
4,9217 gold badges37 silver badges45 bronze badges
asked Jan 1, 2018 at 11:30
-
2you are returning a single object. Send a list of employees and add that employee to the list.It's a trap– It's a trap2018年01月01日 11:32:21 +00:00Commented Jan 1, 2018 at 11:32
-
The actual output is correct if you should stick with the rest principles. If you ask for a user by Id, you don't expect to get a list in return..Marcus Höglund– Marcus Höglund2018年01月01日 11:40:46 +00:00Commented Jan 1, 2018 at 11:40
1 Answer 1
Your code return only a single element. Change it to return a collection by using List
as follows,
public List<Employee> Get(int id)
{
Employee emp = null;
List<Employee> _employees = new List<Employee>();
while (reader.Read())
{
emp = new Employee();
emp.ClientId = Convert.ToInt32(reader.GetValue(0));
emp.ClientName = reader.GetValue(1).ToString();
_employees.Add(emp);
}
return _employees;
}
answered Jan 1, 2018 at 11:31
Explore related questions
See similar questions with these tags.
lang-cs