Abhijit Pandya
Abhijit Pandya

Reputation: 705

Passing an Array of object results in errors

I have created an API in ASP.NET Core 2.2 framework as per below sample

[HttpPost]
[Authorize]
public IActionResult AddInvoiceRest([FromBody]AddInvoiceRetailRest[] InvoiceDetail)
{
}

here AddInvoiceRetailRest is class object. I want to pass multiple objects as array.

I am doing testing with postman. I have passed this array from raw body as per below sample.

{
  "InvoiceDetail": [
    {
      "InvoiceMst": [
        {
          "InvoiceNo": 0,
          "CustId": 0,
          "SubTotal": 93,
          "TaxAmount": 13
        }
      ]
    }
  ]
}

problem is here in api i received blank array without adding [Frombody] and when i add [FromBody] , Api doesn't call and shows error like below

{
    "InvoiceDetail": [
        "The input was not valid."
    ]
}

definition of class is

public class AddInvoiceRetailRest   
    {
        public AddInvoiceMst[] InvoiceMst { get; set; }
        public AddInvoiceItemDetail[] InvoiceItemDetail { get; set; }
        public AddInvoicePaymentDetail[] InvoicePaymentDetail { get; set; }
        [Optional]
        public AddInvoiceItemLogDetail[] InvoiceItemLog { get; set; }
        [Optional]
        public string BillDetail { get; set; }
        [Optional]
        public PumpCartObject[] InvoicePumpCart { get; set; }
        [Optional]
        public InvoiceFeeOrDeposite[] InvoiceFeeOrDeposite { get; set; }
    }

Here in the question, I just put a sample of the request, not all keys. Can someone please let me know what I'm doing wrong?

Upvotes: 0

Views: 2234

Answers (2)

Nkosi
Nkosi

Reputation: 247591

The posted data does not match the expectation of the action.

One option is to create a model that matches the expected data

public class InvoiceDetailModel {
    public AddInvoiceRetailRest[] InvoiceDetail { get; set; }
}

And bind to that in the action

[HttpPost]
[Authorize]
public IActionResult AddInvoiceRest([FromBody]InvoiceDetailModel model) {
    if(ModelState.IsValid) {
        AddInvoiceRetailRest[] invoiceDetail = model.InvoiceDetail;

        //...
    }

    return BadRequest(ModelState);
}

Upvotes: 2

Azhar Khorasany
Azhar Khorasany

Reputation: 2709

Your issue is that you are expecting array in your API but you are passing a single object json and not an array.

Try this:

[
    {
        "InvoiceMst":
        [
            {
                "InvoiceNo": 0,
                "CustId": 0,
                "SubTotal": 93,
                "TaxAmount": 13
            }
        ]
    }
]

Upvotes: 2

Related Questions