how to log out of session MVC Razor visual studio

2019-04-29 17:16发布

问题:

I'm trying to logout from a session in MVC Razor heres what I have in my MainController at the moment:

[HttpPost]
public ActionResult Login(Users user)
{
    if (ModelState.IsValid)
    {
        if (ValidateUser(user.Email, user.Password))
        {

            FormsAuthentication.SetAuthCookie(user.Email, false);
            return RedirectToAction("Index", "Members");
        }
        else
        {
            ModelState.AddModelError("", "");
        }
    }
    return View();
}

private bool ValidateUser(string Email, string Password)
{

    bool isValid = false;

    using (var db = new ShareRideDBEntities())
    {
        var User = db.tblProfiles.FirstOrDefault(u => u.PROF_Email == Email);
        var ut = db.tblProfilesTypes.FirstOrDefault(t => t.TPE_ID == User.PROF_UserType);

        if (User != null)
        {
            if (User.PROF_Password == Password)
            {
                Session["UserID"] = User.PROF_UserID;
                Session["Name"] = User.PROF_FirstName;
                Session["Email"] = User.PROF_Email;
                Session["FullName"] = User.PROF_FirstName + " " + User.PROF_LastName;

                isValid = true;
            }
        }

    }

    return isValid;
}

With this I can login the user and reditect it to his UserCP or user control panel.

I have it so that if the user is not logged in, they will not be able to access the members area with this code in my MembersController:

public ActionResult UserCP()
{
    if (Session["UserID"] == null)
    {
        return RedirectToAction("Index", "Main");
    }
    else
    {
        return View();
    }

}

public ActionResult LogOut()
{
    FormsAuthentication.SignOut();
    return RedirectToAction("index", "main");
}

It will redirect the user back to the main index page if he/she is not logged in yet, but when I test the logout button it redirects me normally but I am still able to go back to the user control panel which is what I don't want to it happen.

Of course I have added

using System.Web.Security;

to use the FormAuthentication.SignOut();

Thanks in advance if anyone can explain this.

回答1:

After FormsAuthentication.SignOut(); You need to call Session.Abandon() that will clear current session and recreate new session on the next request

public ActionResult LogOut()
{
    FormsAuthentication.SignOut();
    Session.Abandon(); // it will clear the session at the end of request
    return RedirectToAction("index", "main");
}