Home > Software design >  ASP.NET Core 5.0 Web API throws error 405 when trying to delete record using HttpDelete
ASP.NET Core 5.0 Web API throws error 405 when trying to delete record using HttpDelete

Time:12-30

I'm building an ASP.NET Core 5.0 Web API application as I mentioned in the title I have an issue when trying to delete a record from the database; I'm getting an error 405 Method Not Allowed response from HttpDelete request.

PS: I have added services.AddCors() and app.UseCors() with default policy.

This is the delete method code

public bool deleteLivreById(int id)
{
    Livre l = _db.Livres.Find(id);
    _db.Livres.Remove(l);
    _db.SaveChanges();
    return true;
}

And this is the HttpDelete method inside the controller

[HttpDelete("{id}/delete")]
   public bool deleteLivreById(int id)
      {
        return  _objGererLivre.deleteLivreById(id);
      }

Finally this is a picture from console when navigating to HttpDelete Url

enter image description here

Edit: This is full code of my controller

namespace GestionLivre.Controllers
{
    [ApiController]
    [Route("test")]
    public class LivreController : Controller
    {
        private IGererLivre _objGererLivre;
        public LivreController(IGererLivre gererLivre)
        {
            _objGererLivre = gererLivre;
        }
        [HttpGet]
        public JsonResult getLivres()
        {
            return Json(_objGererLivre.getLivres());
        }
        [HttpDelete("{id}/delete")]
            public bool deleteLivreById(int id)
        {
               return  _objGererLivre.deleteLivreById(id);
        }
}
}

CodePudding user response:

I opened the screenshot and noticed that you have selected 'GET' as http verb and method type is 'Delete'. Could you please change that and try.

CodePudding user response:

As I understand by default when you're trying to access URL in browser it uses GET method. So we should to pass in header appropriate method(POST,GET,DELETE,PATCH,PUT) If you want to test CRUD methods I recommend you to use Postman or Swagger. Postman much easier to use whether than Swagger which you should to add to service configuration and middleware. Example of Postman: enter image description here

And than configure body like that to return response. enter image description here

Also recommend you to use REST Best Practices. And name urls properly. https://restfulapi.net/resource-naming/#:~:text=2.-,Best Practices,-2.1. Use nouns

  • Related