Im making a post and get request but only inserts one object int List and in the get request always returns a empty array []
using Microsoft.AspNetCore.Mvc;
using rest_api_crud.Models;
namespace rest_api_crud.Controllers
{
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
List<UsersModel> users = new List<UsersModel>();//List of users
[HttpPost(Name = "PostUser")]
public List<UsersModel> Post()
{
users.Add(new UsersModel() { Name = "test", Age = 19 });// inserts only 1 new user to list
return users;
}
[HttpGet(Name = "GetUsers")]
public List<UsersModel> Get()
{
return users; // returns empty array
}
}
}
Because the users list is created each time you send a request, this is because controllers are scoped services. If you want to have it a cross the life time of your app (like a db) you can declare it as static a variable.
Adding @Christophe Devos warning: a List is not thread safe, if multiple requests are all adding, then it's possible that you loose information. Also getting looping it while adding can have strange results. Use locks or a collection from the System.Collections.Concurrent namespace.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments