英文:
Why only inserts one object in list and returns empty array
问题
我正在制作一个帖子和获取请求,但只插入一个对象到列表中,并且在获取请求时始终返回一个空数组[]
使用Microsoft.AspNetCore.Mvc;
使用rest_api_crud.Models;
命名空间rest_api_crud.Controllers
{
[ApiController]
[路由("[控制器]")]
public class UsersController : ControllerBase
{
List<UsersModel> users = new List<UsersModel>();//用户列表
[HttpPost(名称= "PostUser")]
public List<UsersModel> Post()
{
users.Add(new UsersModel() { Name = "test", Age = 19 });// 仅将一个新用户插入到列表中
return users;
}
[HttpGet(名称= "GetUsers")]
public List<UsersModel> Get()
{
返回用户; // 返回空数组
}
}
}
英文:
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
}
}
}
答案1
得分: 2
因为用户列表是每次发送请求时创建的,这是因为控制器是范围服务。如果您希望它跨应用程序的生命周期(就像数据库一样),您可以将其声明为静态变量。
添加 @Christophe Devos 的警告:List
英文:
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<T> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论