[SOLVED] ASP.NET: Update and delete without using HttpPut and HttpDelete

Issue

I found many open-source projects which do not use HttpPut and HttpDelete for updating and deleting. Instead, they add the HttpPost endpoint before their methods, and the functionalities are implemented successfully as well.

What I learned is that we use HttpPut and HttpDelete to update and delete. I am confused.

I have added examples of update methods and delete methods below.

UPDATE:

        [HttpPost]
        public async Task<IActionResult> Edit(int id, NewInvoiceVM invoice)
        {
            var allInvoices = await _service.GetAllAsync();

            var invoicesValidate = allInvoices.ToList().FirstOrDefault(n => n.SupplierName == invoice.SupplierName && n.InvoiceNumber == invoice.InvoiceNumber);
            await _service.UpdateInvoiceAsync(invoice);
            return RedirectToAction(nameof(Index));
        }

DELETE:

        [HttpPost, ActionName("Delete")]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var invoiceDetails = await _service.GetInvoiceByIdAsync(id);
            if (invoiceDetails == null) return View("NotFound");

            await _service.DeleteAsync(id);
            return RedirectToAction(nameof(Index));
        }

Question: Are HttpPut and HttpDelete required for Update and Delete method? If not, when should we use them?

Solution

If you’re implementing an API you have many ways to do it. Using PUT, DELETE, UPDATE etc are all recommended best practices, but there’s no need to use them.

You can write an API that listens for a DELETE request to delete something or you can write an API that listens for a POST request with another parameter that tells it if it’s a delete, or something else. Both work just fine.

The reason you do it a certain way, is so that when other people come to use your stuff, it will be intuitive for them, if you’ve used the best practices recommendation. This goes for PUT/POST as it does for all coding best practices.

Answered By – James

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *