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.jpgFollow 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
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.
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