只插入一个对象到列表中并返回空数组。

huangapple go评论61阅读模式
英文:

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 不是线程安全的,如果多个请求都在添加,则有可能丢失信息。同时在添加时进行循环可能会产生奇怪的结果。请使用锁定或来自System.Collections.Concurrent命名空间的集合。

英文:

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.

huangapple
  • 本文由 发表于 2023年6月21日 22:54:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76524634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定