Categories
Mastering Development

How to [HttpDelete] in asp.NET Core 5.0 Web Api

I have problem with deleting method.

I would like to delete user’s recipe by recipeid.

First question is which type should be delete method?

- void
- Task<bool>
- Task<Entity>

I’ve tried something like this:

My recipe interface:

 public interface IRecipeRepository
        {
            void Update(Recipe recipe);
            Task<bool> DeleteRecipe(int recipeId);
            Task<bool> SaveAllAsync();
        }

Repo:

   public async Task<bool> DeleteRecipe(int recipeId)
    {
        var recipe = await _context.Recipes.
        FirstOrDefaultAsync(e => e.Id == recipeId);

        if (recipe != null)
        {
            _context.Recipes.Remove(recipe);
            return true;
        }
    }   return false;

In my controller:

   [HttpDelete("{id}")]
    public async Task<ActionResult> DeleteRecipe(int id)
    {

         await _recipeRepository.DeleteRecipe(id);

        if (await _recipeRepository.SaveAllAsync())
            return Ok();

        return BadRequest("Failed to delete the recipe");
    }

@Edit

I’ve just changed the code according to your hints.

Now that line is null with :

var recipe = await _context.Recipes.
            FirstOrDefaultAsync(e => e.Id == recipeId);

Screen

Leave a Reply

Your email address will not be published. Required fields are marked *