skip to Main Content

I need help in this code, something wrong is not right lol… I’m trying to run in InMemory database but I wasn’t successful. I’m using

Microsoft.AspNetCore.App 5.0.12

Microsoft.AspNetCore.App 6.0.0

Microsoft.NETCore.App 5.0.12

Microsoft.NETCore.App 6.0.0

Microsoft.WindowsDesktop.App 5.0.12

Microsoft.WindowsDesktop.App 6.0.0

[error image] https://i.stack.imgur.com/5tFrN.jpg

Follow the code below

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Shop.Data;
using Shop.Models;

//Endpoint = URL
//http://localhost:5000
//https://localhost:5001

[Route("categories")]
public class CategoryController : ControllerBase
{
    [HttpGet]
    [Route("")]
    public ActionResult<List<Category>> Get()
    {
        return new List<Category>();
    }

    [HttpGet]
    [Route("{id:int}")]
    public ActionResult<Category> GetById(int id)
    {
        return new Category();
    }


    [HttpPost]
    [Route("")]
    public async Task<ActionResult<List<Category>>> Post(
        [FromBody] Category model,
        [FromServices] DataContext context)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        context.Categories.Add(model);
        await context.SaveChangesAsync();
        return Ok(model);
    }


    [HttpPut]
    [Route("{id:int}")]
    public ActionResult<List<Category>> Put(int id, [FromBody] Category model)
    {
        if (id != model.Id)
            return NotFound(new { message = "Categoria não encontrada" });

        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        return Ok(model);
    }

    [HttpDelete]
    [Route("{id:int}")]
    public ActionResult<List<Category>> Delete()
    {
        return Ok();
    }

2

Answers


  1. Chosen as BEST ANSWER

    I'm sorry guys, I installed Swashbuckle.AspeNetCore.Swagger 5.0.0 and was calling it in Startup.cs. I removed both and it worked perfectly.


  2. The error why you don’t define a parameter in your delete method to get the {id:int} that should be passed through the route

    [HttpDelete]
    [Route("{id:int}")]
    public ActionResult<List<Category>> Delete(int id)
    {
        return Ok();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search