What better way to leave a value in session?

Asked

Viewed 304 times

1

What better way to leave a session value on Asp.net mvc ?

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

For example:

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

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

  • If possible give more information, example, what data you want to store and for what?

  • Hello @Renan, I edited with an example, I do not know if it was clear

1 answer

1

You can use the object Session to store patient information.

The Session object allows the developer to obtain the data, previously persisted in the session, for a given 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, many data may trigger scalability issues.

Storing patient information in Ssion:

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

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

Retrieving data from Session and reusing:

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

Accessing data in view with Razor:

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

You lose the information from Session when for example the application is restarted (example: Global.asax or Web.Config file 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 statistical class:

public static class SessionContext
{    
        public static Paciente Paciente
        {
            get 
            {
                return (Paciente)HttpContext.Current.Session["Paciente"];
            }
            set 
            {
                HttpContext.Current.Session["Paciente"] = value;
            }
        }
}
  • Can Session happen if lost? Could be used to navigate between all controllers/areas ?

  • You lose the information from Session when for example when the application restarts (example: Global.asax or Web.Config file is modified). Yes, Session information can be accessed between controllers/areas.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.