Keep data between sessions

6

I have an ASP.Net MVC project where I generate a report that requires a lot of the machine's processing feature.

I have a Action that generates and another that returns the report data in an Object List, so I thought that by creating a static variable, I could save the data in the report and return it as needed.

private static List<MeuObjeto> DadosRelatorio = new List<MeuObjeto>();
public ActionResult MinhaAction ()
{
    // Limpando dados que já estavam.
    if (DadosRelatorio.Count() > 0)
    {
        DadosRelatorio.Clear();
    }

    ...
    // Preenchendo DadosRelatorio
    ...
}
public ActionResult OutraAction ()
{
  return Json(DadosRelatorio, JsonRequestBehavior.AllowGet);
}

The problem is that when 2 or more users simultaneously generate a report, the data in one overwrites another.

I thought that when creating a static variable the framework itself would manage a variable for each on the server, but that is not the case, the same variable is for every user.

Is there an alternative?

    
asked by anonymous 13.09.2015 / 14:58

2 answers

8

In fact, the static variable can not be used. You need to create a session-based caching system or at least keep the information within the same session.

public ActionResult MinhaAction() {
    Session["relatorioX"] = MontaRelatorio();
    ...
}
public ActionResult OutraAction() {
  return Json(Session["relatorioX"], JsonRequestBehavior.AllowGet);
}

The MontaRelatorio() probably returns a List<MeuObjeto> .

This is obviously a simplification, errors can occur if used like this but does what you were doing keeping the data per session rather than maintaining per instance of the application.

I believe that in this case you can use TempData instead of Session with no problems.

I do not know if this fits all needs but solves the problem according to what was specified in the question.

I would avoid putting a large amount of data between sessions but it is a simple solution.

This answer in SO has a solution with caching. Another using the framework cache system itself.

ASP.Net Core has a more flexible new cache system (4)).

    
13.09.2015 / 15:33
0

One suggestion: Use different names for reports based on user identifiers (if applicable), where you can, via a BATCH that runs 1x a day, delete the oldest reports based on your dates (if applicable) .

In this way you will have "user-dependent" reports, obviously not dependent on perennial variables.

    
30.09.2015 / 20:06