首页 > 解决方案 > 如何在 C# .NET Web API 中接收和拆分对象数组

问题描述

我在前端有一个导入的 excel 文件,在保存时,它将 excel 数据作为对象数组发送到我们的.NET Web API控制器[FromBody],然后stored procedure通过DataTable. 数组中的每个对象都是 excel 文件中的一行。

编辑我的数据是从前端通过POSTwith发送的httpOptions body:。发送到控制器的数据如下所示:

[
{name: "Bob", position: "Software Developer", sales: 100000}
 {name: "Ted", position: "Software Developer", sales: 100568}
 {name: "George", position: "Software Developer", sales: 40000}
]

C#控制器中,我怎样才能接收这个包含未知数量对象的数组并使用它?目前我正在使用一个示例forEach块,它最初只接受一个 ID 数组,但这不起作用,因为现在我正在尝试发送一个对象数组并且我不能.split在它上面使用:

[Route("api/myRoute")]
[HttpPost]
    public async Task<IHttpActionResult> uploadExcelData
                (
                  [FromBody] Array excelRows
    )
            {
                 string[] aryExcelRowsObjects;

                 DataTable dataTable = new DataTable();
                 dataTable.Columns.Add(new DataColumn("name", typeof(string)));
                 dataTable.Columns.Add(new DataColumn("position", typeof(string)));
                 dataTable.Columns.Add(new DataColumn("sales", typeof(int)));

                 // this is the example I'm using and it no longer works as you can't use .Split() on an array. What should I change it to?
                 aryExcelRowsObjects = excelRows.Split(','); 

                // this is the example I'm using and I don't think it accounts for adding multiple columns into a row
                    foreach (string s in aryExcelRowsObjects)
                    {
                        dataTable.Rows.Add(s);
                    }

            }

我应该在代码注释的两个部分中更改什么?

标签: c#angularasp.net-web-apidatatablescontroller

解决方案


您拥有的数据类型没有排列,因此您现在发送回的数组无法绑定到字符串,因此excelRows为空。因此,当您尝试拆分时excelRows,它会在您的脸上炸开。

让您的控制器接受您发送的数据...

假设您要退货Employee[]

public class Employee
{
    public string Name { get; set; }
    public string Position { get; set; }
    public int Sales { get; set; }
}

现在,显然你不能调用string.Split. Employee[]但是你可以做任何可以用来[]喜欢for, foreach,Select等等的事情。

foreach(var employee in employees)
{
    // do stuff...
}

推荐阅读