Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

[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" } ] }

if you could recommend me what would be the best option to work this

like image 374
esantiago Avatar asked Mar 05 '23 08:03

esantiago


1 Answers

Make a DTO class as follows:

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

Where Data is as follows:

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

Then in your POST method:

[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");
    }
}
like image 196
TanvirArjel Avatar answered Mar 07 '23 00:03

TanvirArjel