Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing not working when sending a DELETE request to an HttpDelete action

I have a ProductsController with only one View - Index.cshtml.

The following 3 action methods are inside of this controller:

//http://localhost:55555/products
[HttpGet]
public IActionResult Index()
{
}

//http://localhost:55555/products
[HttpPost]
public IActionResult Index(ProductViewModel product)
{
}

//http://localhost:55555/products/1
[HttpDelete("{id}")]
public IActionResult Index([FromRoute] int id)
{
}

Get works perfectly fine when I go to /products. Post works perfectly fine when I create a new product using /products. Delete does not work at all, I am getting a 404 not found for /products/9. I am using a standard AJAX request w/ type: DELETE.

I am using the default MVC conventional routing settings:

        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");

Here is what my AJAX Request looks like:

$(".js-delete-product").click(function () {
    $.ajax({
        type: "DELETE",
        url: "products/" + $(this).data("id"),
        success: onDeleteSuccess
    });
});

I also tried sending a DELETE request in postman to http://localhost:55555/products/1 to make sure it wasn't my jquery ajax and still 404 not found.

UPDATE: If I send a DELETE request to just http://localhost:55555/products it goes into the function, but as you would expect the id param is set to null. Any idea why this is happening? I only want it to go into the delete method if a param is passed, but when a param is passed it doesn't go in (404 not found).

like image 548
Blake Rivell Avatar asked Dec 19 '16 17:12

Blake Rivell


2 Answers

Include the route parameter for id on the [HttpDelete] attribute:

[HttpDelete("{id}")]
public IActionResult Index([FromRoute] int id)
{
}
like image 169
Justin Saraceno Avatar answered Sep 29 '22 12:09

Justin Saraceno


Finally found the answer to this, but only from trial and error. I have no idea why it only works this way.

//http://localhost:55555/products/1

[HttpDelete("products/{id}")]
public IActionResult Index([FromRoute] int id)
{
}

I have no idea why I should have to specify the controller name as it should already be assumed based off of this setting:

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");

If someone can further explain why this is the case that would be great.

like image 25
Blake Rivell Avatar answered Sep 29 '22 12:09

Blake Rivell