What is the best way to leave a session value?

1

What is the best way to leave a value in session in asp.net mvc?

This value can be changed by the user, when he wants, but as he uses the system, he will use the value of that session ...

For example:

Set a Patient, then, as you navigate the system, the information that it accesses, will be that patient, not others.

What better way to do this? Session? static in a base controller?

    
asked by anonymous 24.10.2014 / 13:09

1 answer

1

You can use the session to store patient information.

The Session object allows the developer to get the data, previously persisted in the session, for a fixed time (configurable, but the default is 20 minutes). But, use this feature sparingly, storing only the required data, since session data is stored by default in memory, too much data can trigger scalability issues.

Storing patient information in session:

public ActionResult Index()
{
    Paciente paciente = new Paciente
    {
        ID = 1,
        Nome = "Fulado"
    };

    Session["Paciente"] = paciente;
    return RedirectToAction("Navegar");
}

Getting session data and reusing:

public ActionResult Navegar()
{
    Paciente paciente = Session["Paciente"] as Paciente;    
    return View(paciente);
}

Accessing data in the view with Razor:

@{ var pacienteDaSession = Session["paciente"]; }

You lose the session information when the application is restarted (example: Global.asax or Web.Config is modified);

I believe there is no better way, but rather a more organized way.

Examples:

Using properties inside the Controller:

public class MeuController : Controller
{
    public Paciente Paciente
    {
        get
        {
            return (Paciente)Session["Paciente"];
        }
        set
        {
            Session["Paciente"] = value;
        }
    }
}

Using properties within a static class:

public static class SessionContext
{    
        public static Paciente Paciente
        {
            get 
            {
                return (Paciente)HttpContext.Current.Session["Paciente"];
            }
            set 
            {
                HttpContext.Current.Session["Paciente"] = value;
            }
        }
}
    
24.10.2014 / 14:30