Home > Blockchain >  ASP.NET: Update and delete without using HttpPut and HttpDelete
ASP.NET: Update and delete without using HttpPut and HttpDelete

Time:02-28

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?

CodePudding user response:

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 paramater 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.

CodePudding user response:

Historically, web browsers did not have native support for PUT, PATCH, DELETE, and other verbs. They only support GET and POST. API's that implemented PUT etc. had to do it by sending a POST with a hidden field (often named _method) to pretend that they were sending something other than a POST.

For this reason, many projects just didn't think it was worth implementing.

CodePudding user response:

There is already a example how Microsoft does it. This is the way you should do it in most cases (seems you are using .Net?).

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-6.0&tabs=visual-studio#the-deletetodoitem-method

Maybe the people in the repositories you saw just made mistakes.

  • Related