3

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
2
  • 2
    you are returning a single object. Send a list of employees and add that employee to the list. Commented 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.. Commented Jan 1, 2018 at 11:40

1 Answer 1

4

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.