Home > database >  ASP.NET Core routes GET call to DELETE method
ASP.NET Core routes GET call to DELETE method

Time:02-14

I have an ASP.NET Core web API controller with (among others) two methods that have the same signature.

Shortened down, this looks as follows:

[Route("my/route")]
public class MyApiController : ApiController
{
    [HttpGet("{*id}", Order = 2)]
    [Route("{*id}", Order = 2)]
    public MyObject Load([FromUri] String id) => new MyObject();
    
    [HttpDelete("{*id}", Order = 1)]
    [Route("{*id}", Order = 1)]
    public void Delete([FromUri] String id)
    {
    }
}

Now, I am issuing a call:

GET my/route/123/456

Shockingly, this call ends up in the Delete method. I literally have a breapoint in the first line of my (in real life, non-empty) Delete method, and the Immediate window in VS tells me HttpContext.Request.Method is "GET", yet I end up in the method explicitly marked as HttpDelete.

What is going on here? Luckily, my call happened from within an automated test to test the web API, but if someone had issued that call to retrieve actual data from the DB, they would have ended up deleting that data instead. Is there any misunderstanding on my side with respect to the [HttpDelete] attribute?

CodePudding user response:

You don't have to use route attribute and order parameter. It might be cause this situation.

[Route("my/route")]
public class MyApiController : ApiController
{
    [HttpGet("{*id}")]
    public MyObject Load([FromUri] String id) => new MyObject();
    
    [HttpDelete("{*id}")]
    public void Delete([FromUri] String id)
    {
    }
}

CodePudding user response:

If you have an [ApiController] attribute, you have to remove it since you will need full explicit route attribute. Or it is much better to use explicit routes

[Route("my/route")]
public class MyApiController : ApiController
{
    [HttpGet("my/load/{id}")]
    public MyObject Load(string id) => new MyObject();
    
     [HttpDelete("my/delete/{id}")]
     [HttpGet("my/delete/{id}")]
    public void Delete(string id)
    {
    }
}
  • Related