-3

I have a list of string data, I want to add some values there and see them. There is a method for adding data and another method for printing. after adding some data get an empty list during print.

Here Is my code

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    private List<string> dataList = new List<string>();

    [HttpGet]
    public async Task<IActionResult> GetData()
    {
        return Ok(dataList);
    }
    
    [HttpPost]
    public async Task<IActionResult> AddData()
    {
        var testData = new List<string>() { "ab", "cd", "efg" };

        foreach(var data in testData)
        {
                dataList.Add(data);
        }
        return Ok();
    }
}
Rand Random
  • 7,300
  • 10
  • 40
  • 88
IdleMan
  • 37
  • 5
  • `get an empty list during print.` where and how do you print? – Rand Random Jun 08 '22 at 12:56
  • 3
    Did you check what is lifecycle of `ControllerBase` ? ... i'm pretty sure that it is create new for every request ... use some persistance date store – Selvin Jun 08 '22 at 12:58
  • @RandRandom It is an API controller. I will get a list of data with a success status code in response. – IdleMan Jun 08 '22 at 12:58
  • @Selvin It's working the same for Controller and ControllerBase. – IdleMan Jun 08 '22 at 13:00
  • is `Task` the correct return value for the method? shouldn't it say atleast somewhere that is returns a list of strings? – Rand Random Jun 08 '22 at 13:02
  • @RandRandom I think so. because if I return the Ok(dataList) from AddData() method, It's giving the expected response. – IdleMan Jun 08 '22 at 13:07
  • 2
    for testing purposes, you could make `dataList` `static` so it persists across requests. But really you need some data storage mechanism to persist the value between requests. – Jonesopolis Jun 08 '22 at 13:10
  • My asp days are pretty outdated, but have a look at this: https://stackoverflow.com/questions/1763775/asp-net-mvc-controller-lifecycle - as @Selvin already mentioned the life cycle seems to be per request so the field `dataList` will be initliaized everytime - no idea, how to share data, added the tag `asp.net` to get attention of `asp.net` developers – Rand Random Jun 08 '22 at 13:13
  • notice that making it static raises question like: does it share between users/sessions? is thread-safe a concern? – Rand Random Jun 08 '22 at 13:32
  • and when the site is restarted, the old values are lost. As was mentioned before, this may be fine for an initial test. If more is needed, use some more permanent storage – Hans Kesting Jun 08 '22 at 13:49

1 Answers1

1

Use the static list. I hope it will work for you.

private static List<string> dataList = new List<string>();
shuvo
  • 164
  • 1
  • 8