Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 返回asp.net WebAPI中的数组对象_C#_Asp.net_Angularjs_Asp.net Web Api - Fatal编程技术网

C# 返回asp.net WebAPI中的数组对象

C# 返回asp.net WebAPI中的数组对象,c#,asp.net,angularjs,asp.net-web-api,C#,Asp.net,Angularjs,Asp.net Web Api,我想创建WEB API,它将输入发送到Angular。我想以JSON格式作为数组发送数据 下面是我的代码: [HttpGet] [ActionName("GetEmployeeByID")] public Employee Get(int id) { Employee emp = null; while (reader.Read()) { emp = new Employee(); emp.ClientId = Convert.ToInt3

我想创建WEB API,它将输入发送到Angular。我想以JSON格式作为数组发送数据

下面是我的代码:

[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;
}
实际输出:

{"ClientId":15,"ClientName":"Abhinav Singh"}
[{"ClientId":15,"ClientName":"Abhinav Singh"}]
预期输出:

{"ClientId":15,"ClientName":"Abhinav Singh"}
[{"ClientId":15,"ClientName":"Abhinav Singh"}]

您的代码只返回一个元素。使用
列表将其更改为返回集合,如下所示:

  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;
     }
公共列表获取(int-id)
{
员工emp=null;
列表_employees=新列表();
while(reader.Read())
{
emp=新员工();
emp.ClientId=Convert.ToInt32(reader.GetValue(0));
emp.ClientName=reader.GetValue(1.ToString();
_添加(emp);
}
返回(u)员工;;
}

返回的是单个对象。发送一份员工列表,并将该员工添加到列表中。如果您坚持其他原则,则实际输出是正确的。如果您通过Id请求一个用户,您不希望得到一个列表作为回报。。