c# - 如何在 C# .NET Web API 中接收和拆分对象数组
问题描述
我在前端有一个导入的 excel 文件,在保存时,它将 excel 数据作为对象数组发送到我们的.NET Web API
控制器[FromBody]
,然后stored procedure
通过DataTable
. 数组中的每个对象都是 excel 文件中的一行。
编辑我的数据是从前端通过POST
with发送的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);
}
}
我应该在代码注释的两个部分中更改什么?
解决方案
您拥有的数据类型没有排列,因此您现在发送回的数组无法绑定到字符串,因此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...
}
推荐阅读
- c# - 有没有办法结合foreach循环
- haskell - 如何使用 Haddock 记录类型类约束?
- django - 在管理员中上传图像时,出现错误:不允许文件扩展名 'jpg'。允许的扩展名是:''
- python - 从 pycharm 运行 dev_appserver.py 时出现 ImportError
- apache-spark - apache spark执行器和数据本地化
- php - 从php中的字符串中删除字母数字单词
- javascript - 使用猫鼬的对象引用
- php - Slim Framework如何在拦截器中按名称捕获路由参数
- c# - 在 Web API (.Net Framework) 中创建自定义 AuthorizeAttribute
- reactjs - 使用 redux,当状态树中的状态有效更改时,为什么 mapStateToProps() 没有在 props 中显示状态?