简体   繁体   English

如何在 ASP.NET Core Web API 中发布对象列表

[英]How to post list of object in ASP.NET Core Web API

I have seen several tutorials in which to send a json object with POST method.我看过几个教程,其中使用 POST 方法发送 json 对象。

[HttpPost]
public async Task<IActionResult> createEntity([FromBody]Entity entity)
{
    try
    {
         await _repository.Entity.CreateEntityAsync(entity);
         return Ok();
     }
     catch (Exception ex)
     {
          return StatusCode(500, "Internal server error");
      }
}

This does the job correctly这可以正确完成工作

Now if I want to send:现在,如果我想发送:

{ "ID":1, "data":[ { "value1":"xxxx", "value2":"yyyy" }, { "value1":"zzzz", "value2":"wwww" } ] } { "ID":1, "data":[ { "value1":"xxxx", "value2":"yyyy" }, { "value1":"zzzz", "value2":"wwww" } ] }

if you could recommend me what would be the best option to work this如果你能推荐我什么是最好的选择

Make a DTO class as follows:制作一个 DTO 类,如下所示:

public class YourDto
{
   public int ID {get; set;}
   public List<Data> Data {get; set;}
}

Where Data is as follows:其中Data如下:

public class Data
{
   public string Value1 {get; set;}
   public string Value2 {get; set;}
}

Then in your POST method:然后在你的 POST 方法中:

[HttpPost]
public async Task<IActionResult> createEntity([FromBody]YourDto yourDto)
{
    try
    {
         // do whatever you want to do with the yourDto object

         return Ok();
    }
    catch (Exception ex)
    {
          return StatusCode(500, "Internal server error");
    }
}

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

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