Cookie is not delete in mvc(c#)

15,586

Solution 1

Thank you AndreyMaybe, Ant P

This code work:

Response.Cookies.Clear();

FormsAuthentication.SignOut();     

HttpCookie c = new HttpCookie("login");
c.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(c);

Session.Clear();

Solution 2

You're changing the value of the cookie, but you're not adding it to the response again!

FormsAuthentication.SignOut();
HttpCookie c = Request.Cookies[FormsAuthentication.FormsCookieName];
c.Expires = DateTime.Now.AddDays(-1);

// Update the amended cookie!
Response.Cookies.Set(c)

Session.Clear();
/* Get rid of this, it will break the above by clearing
 * the cookie collection that you've just updated. */
// Request.Cookies.Clear();
// Response.Cookies.Clear();

Solution 3

There is a much easier way to determine if the user is authenticated, as per this post How to check if user is authorized inside Action

After you have called the FormsAuthentication.SetAuthCookie(), you can call User.Identity.IsAuthenticated. No need to set your own cookies.

If you do it like this, the FormsAuthentication.SignOut() will destroy the correct cookie

Share:
15,586
itmanir
Author by

itmanir

Updated on June 04, 2022

Comments

  • itmanir
    itmanir almost 2 years

    I want to make login and logOut functions in mvc4. In login func, if login cookie exist and not empty, user is in signIn mode, else redirect to login page. In logOut func, all cookies and sessions clear and redirect to login func, but in login func login cookie exist!

    Login:

    public ActionResult Login()
            {
                if (Request.Cookies["login"] != null)
                {
                    string login = Request.Cookies["login"].Value.ToString();                
    
                    if (login != string.Empty)
                    {
                        //Get from service
                        Service srv = new Service();
                        UserItem userItem = srv.getUserItem(login);                    
                        srv.Close();
    
                        Session.Timeout = 30;
                        Session["login "] = login;
                        Session["userId"] = userItem.No;
                        Session["firstName"] = userItem.FirstName;
                        Session["lastName"] = userItem.LastName;
                        string loginName = userItem.LoginName;                    
    
                        FormsAuthentication.SetAuthCookie(loginName, false);
    
                        return Redirect(“Index”);
                    }
                    else 
                    {
                        Return redirect("http://mySite/SignIn.aspx");
                    }
                }
                else
                {
                    Return redirect("http://mySite/SignIn.aspx");                    
                }
            }
    

    LogOut:

    public ActionResult LogOut()
            {
                string login = Session["login"].ToString();
    
                Request.Cookies["login"].Value = "";
                Response.Cookies["login"].Value = "";
    
                FormsAuthentication.SignOut();
                HttpCookie c = Request.Cookies[FormsAuthentication.FormsCookieName];
                c.Expires = DateTime.Now.AddDays(-1);
    
                Session.Clear();
                Request.Cookies.Clear();
                Response.Cookies.Clear();
    
                //FormsAuthentication.Initialize();
                //string strRole = String.Empty;
                //FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, "", DateTime.Now, DateTime.Now.AddMinutes(-30), false, strRole, FormsAuthentication.FormsCookiePath);
                //Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat)));
    
                //Session.Abandon();
    
                //// clear authentication cookie
                //HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
                //cookie1.Expires = DateTime.Now.AddYears(-1);
                //Response.Cookies.Add(cookie1);
    
                //// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
                //HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
                //cookie2.Expires = DateTime.Now.AddYears(-1);
                //Response.Cookies.Add(cookie2);
    
                //FormsAuthentication.RedirectToLoginPage();               
    
                return RedirectToAction("Login", "Usr");
            }
    

    Web.config:

    <authentication mode="Forms">
          <forms loginUrl="~/Usr/Login" timeout="30" />
        </authentication>
    

    I am trying comment codes, even comment this line:

    FormsAuthentication.SignOut();
    

    Even I set the cookie value to "", but in login page this cookie have old value! And trying several ways to clear cookie like set expire to one day later. But…

    Thanks

  • itmanir
    itmanir almost 11 years
    I need this cookie, because this cookie is set in a service(my signIn page)
  • Ant P
    Ant P almost 11 years
    Then you are not implementing it properly. If you update the cookie and then set it, it will be returned and updated (expired) in the response. If this isn't happening, then you are clearing it again before the response is sent.
  • itmanir
    itmanir almost 11 years
    Thanks a lot, Ant P, AndreyMaybe. its work, but I cant answer my question until 8 hour