Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return OrderID after Post instead of Entire Post

I’m trying to achieve this in my API after posting to my API as a 201 Status Code Return:

{
   orderId: "4"
}

But instead I’m getting this back after I POST:

{
    "orderID": 4,
    "identifier": "Udacity",
    "customer": "Assassin's Creed",
    "items": [
        {
            "id": 3,
            "orderID": 4,
            "productId": 5000,
            "quantity": 10
        }
    ]
}

This is my code for returning after POST:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[HttpPost]
        public async Task<ActionResult<Order>> PostOrder(PostOrderDTO postOrderDto)
        {

            var order = new Order(postOrderDto.Identifier, postOrderDto.Customer);

            var json = JsonConvert.SerializeObject(order);

            var content = new StringContent(json, Encoding.UTF8, "application/json");

            _context.Order.Add(order);
            await _context.SaveChangesAsync();

            var basket = await GetBasketItems(postOrderDto.Identifier);
            var newOrderId = order.OrderID;

            foreach (var item in basket.Items)
            {
                var orderLine = new OrderLine
                {
                    OrderID = newOrderId,
                    ProductId = item.ProductId,
                    Quantity = item.Quantity
                };

                _context.OrderLine.Add(orderLine);
            };

            await _context.SaveChangesAsync();

            return CreatedAtAction("GetOrder", new { id = order.OrderID }, order);
        }

Is there any way to achieve this? Do I do this?

return CreatedAtAction("GetOrder", new { id = order.OrderID });

I don’t that worked the last time I tried, thanks for any help in advance

>Solution :

I would use this code

         [HttpPost]
        public async Task<ActionResult> PostOrder(PostOrderDTO postOrderDto)
        {
            .... your code

            return Ok( new { id = order.OrderID } );
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading