How to log out of a visual studio MVC Razor

I am trying to exit a session in MVC Razor heres, which 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 log into the user’s system and redo it on my UserCP or user control panel.

I have this so that if the user does not log in, they will not be able to access the members area using this code in my MemberController:

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 to the index home page if he / she is not already logged in, but when I test the exit button, it redirects me normally, but I can still return to the user control panel, which I don’t want to happen .

Of course I added

using System.Web.Security;

use FormAuthentication.SignOut ();

Thanks in advance if anyone can explain this.

+5
2

FormsAuthentication.SignOut(); Session.Abandon(),

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

Session.Clear Session.RemoveAll ; . , , . Session_OnEnd .

Session.Abandon , , . . , . Session_OnEnd , Abandon. .

public ActionResult LogOut()
{
    FormsAuthentication.SignOut();
    Session.Clear();
    Session.RemoveAll();
    Session.Abandon(); 
    return RedirectToAction("index", "main");
}
0

Source: https://habr.com/ru/post/1546896/


All Articles