简体   繁体   English

ASP.NET C#REST WEB API-POST多个JSON值

[英]ASP.NET C# REST WEB API - POST Multiple JSON values

I am struggling to find a solution to my problem: I have a really simple Web API in C# that GET, POST, PUT and DELETE employees nicely, but everything working with a simple JSON input: 我正在努力找到解决问题的方法:我在C#中有一个非常简单的Web API,可以很好地使GET,POST,PUT和DELETE员工工作,但所有工作都使用简单的JSON输入:

{
   "FirstName": "Sam 10",
   "LastName": "Wicht 10",
   "Gender": "Male",
   "Salary": 140000
}

What I want to do is to POST a lot of employees, like: 我想做的是招聘很多员工,例如:

"employees": [{
   "FirstName": "Sam 10",
   "LastName": "Wicht 10",
   "Gender": "Male",
   "Salary": 140000
}, {
   "FirstName": "Sam 11",
   "LastName": "Wicht 11",
   "Gender": "Male",
   "Salary": 99000
}]

And in my C# Code, I receive, for instance a List<Employee> containing every employee from JSon and then I loop a For Each ... updating each. 然后在我的C#代码中,我收到一个List<Employee>其中包含JSon中的每个员工,然后循环执行For Each ...更新每个员工。

Performance-wise, is this something really bad? 性能方面,这真的很糟糕吗? Thinking I can limit the List size and avoid running any code if .Count() is higher than X, can you guys please let me know how to retrieve this from the JSON input? 我想我可以限制List的大小,并且如果.Count()大于X,可以避免运行任何代码,请让我知道如何从JSON输入中检索此内容吗?

This is the class Employee I have: 这是我的班级雇员:

public partial class Employee
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public Nullable<int> Salary { get; set; }
}

Should I include a new Class that represents an IEnumerable<Employee> with all the parameters? 是否应该包括一个代表所有参数的IEnumerable<Employee>的新类?

This is for learning and testing purposes, and I tried to retrieve [FromBody] List<Employee> myVariableName; returns null; 这是出于学习和测试目的,我试图检索[FromBody] List<Employee> myVariableName; returns null; [FromBody] List<Employee> myVariableName; returns null;

You're getting null because you have an enclosing employee object in your sample json. 由于在示例json中有一个封闭的employee对象,因此您将获得null。 POST instead: 改为POST:

[{
   "FirstName": "Sam 10",
   "LastName": "Wicht 10",
   "Gender": "Male",
   "Salary": 140000
}, {
   "FirstName": "Sam 11",
   "LastName": "Wicht 11",
   "Gender": "Male",
   "Salary": 99000
}]

And that will match your controller definition of: 这将与您的控制器定义相匹配:

public ActionResult Post(List<Employee> employees)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM