How to maintain a Session after re-running an application?

Asked

Viewed 275 times

1

In my MVC 5 project, a session with the user data is created in the login and after the re-execution of the application the Session no longer exists, however, the authentication Coockie still exists.

What can I do to keep you both active or destroy you both?

[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (!this.ModelState.IsValid)
        return View(model);

    if (Membership.ValidateUser(model.Usuario, model.Senha))
    {
        Session.Add("Usuario", new UsuarioModel { Nome = "Eu", Login = "Filipe"});
        FormsAuthentication.SetAuthCookie(model.Usuario, false);
        if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
            && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
        {
            return this.Redirect(returnUrl);
        }

        return this.RedirectToAction("Index", "Home");
    }

    this.ModelState.AddModelError(string.Empty, "O usuário ou a senha são inválidos");

    return View(model);
}

1 answer

2

By default the storage mode of the Session is In-Proc, i.e., the information is stored in the server memory, however if the application is restarted your Session information is lost.

An alternative to keeping your Session data even after restarting your application is to change the storage mode of Session.

You can use the option Sqlserver which stores session information in the database, another option is Stateserver which stores session information in a separate process on the server, isolating the state of the Session of your application.

To change the available modes, simply add the tag <sessionState> within the tag <system.web>, in the Web.Config file and configure as your need.

Here are some links for more details (in English): Link1 Link2 Link3

Browser other questions tagged

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