Search code examples
asp.net-core-mvcasp.net-apicontroller

Asp.Net Core MVC How to handle The request matched multiple endpoints


I'm working on app with recipes. I'm wrote delete recipe method and this worked fine but then had to add method which delete photo from recipe. Working on Core 3.1.1 with Api's

I'm getting this error when I try to have 2 "Delete" methods enter image description here

My code:

namespace RecipesApp.API.Controllers
{
    [Authorize]
    [Route("api/users/{userId}/recipes/{recipeId}/photos")]
    [Route("api/users/{userId}/recipes")]
    [Route("api/[controller]")]
    [ApiController]
    public class RecipesController : ControllerBase
    {




// http://localhost:5000/api/users/{userId}/recipes/{id}
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteRecipe(int userId, int id)
        {


        }


  [HttpDelete("{id}")]
        public async Task<IActionResult> DeletePhoto(int recipeId, int id)
        {



        }

Solution

  • The Route annotation must be unique on the class definition, and is mainly used to prefix the controller path. The Http* annotations go on the controller public methods, their value represents the unique path assigned to each one.

    Combining both (Route and Http*) you will get the full template path assigned to your method. According to this, your code must look like this:

    namespace RecipesApp.API.Controllers
    {
        [Authorize]
        [Route("/api/users/{userId}/[controller]")]
        [ApiController]
        public class RecipesController : ControllerBase
        {
    
            // /api/users/{userId}/recipes/{id}
            [HttpDelete("{id}")]
            public async Task<IActionResult> DeleteRecipe(int userId, int id)
            {
                //
            }
    
    
            // /api/users/{userId}/recipes/{id}/photos
            [HttpDelete("{id}/photos")]
            public async Task<IActionResult> DeletePhoto(int recipeId, int id)
            {
                //
            }
        }
    }