Search code examples
c#requestasp.net-core-webapiasp.net-core-5.0http-method

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


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);
        }
}
}

Solution

  • 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 HTTP methods I'll 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 resources properly. https://restfulapi.net/resource-naming/#:~:text=2.-,Best%20Practices,-2.1.%20Use%20nouns