0

I have a request where there is multple object in the json file . I need to add them via PostMan

This is my Dto

public class CustomerDto 
{
   [Required(ErrorMessage = "The Id is required")]       
   public int Id { get; set; }
   [Required(ErrorMessage = "The FirstName is required")]
   public string FirstName { get; set; }            

}

This is my ServiceClass, this is where i add it to a class level customerlist object for now.

   public static class CustomerService
   {
    public static List<CustomerDto> customerList = new List<CustomerDto>()  {
                                                                             new CustomerDto { FirstName = "Joe", Id = 1},
                                                                             new CustomerDto { FirstName = "Rose", Id = 2},
                                                                             new CustomerDto { FirstName = "Sid", Id = 3 },
                                                                            
                                                                            };
  }

This is my Api Post Request

    [HttpPost]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
    public ActionResult<VillaDTO> addCustomer([FromBody]CustomerDTO customerDTO)
    {
        if (customerDTO== null)
        {
            return BadRequest(villaDTO);
        }           
   
        CustomerService.customerList.Add(customerDTO);

        return Ok(customerDTO);
    }

I try to debug but before it hits the method call it throws the exceptions. I just want to know how my object is populated first. enter image description here Thanks for having a look

After updating a bad Json using Json Validator . I now get this error message. DTO seems to be the issue .

    {
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-58f71fb73f3af573db60c11551cb2093-792cd201f9e3f0d3-00",
  "errors": {
    "$": [
      "The JSON value could not be converted to CustomerManagementAPI.Model.Dto.CustomerDto. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
    ],
    "customerDTO": [
      "The customerDTO field is required."
    ]
  }
}
user3920526
  • 404
  • 4
  • 20

1 Answers1

1

If you're trying to post a collection

[
    {
        "firstName": "John",
        "id": 6
    },
    {
        "firstName": "Anna",
        "id": 7
    }
]

Have your action accept a collection as well

public IActionResult addCustomer([FromBody] List<CustomerDto> customers) { }
Jasen
  • 14,030
  • 3
  • 51
  • 68