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

.net-core asp.net-web-api c# entity-framework-core

Question

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

1
2
3/18/2019 3:06:39 PM

Accepted Answer

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");
    }
}
2
3/15/2019 4:18:42 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow