How do you clear cookies using asp.net mvc 3 and c#?

前端 未结 3 874
攒了一身酷
攒了一身酷 2020-11-29 02:56

Ok, so I really think I am doing this right, but the cookies aren\'t being cleared.

 Session.Clear();
 HttpCookie c = Request.Cookies[\"MyCookie\"];
 if (c !         


        
相关标签:
3条回答
  • 2020-11-29 03:13

    Cookies are stored on the client, not on the server, so Session.Clear won't affect them. Also, Request.Cookies is populated by IIS and given to your page with each request for a page; adding/removing a cookie from that collection does nothing.

    Try performing a similar action against Response.Cookies. That should cause your client to overwrite the old cookie with the new one, causing it to be expired.

    0 讨论(0)
  • 2020-11-29 03:23

    I did this and it worked for clearing (not deleting) a session cookie:

    HttpContext.Response.Cookies.Set(new HttpCookie("cookie_name"){Value = string.Empty});
    

    Based on Metro's response I created this extension method to make the code reusable in any controller.

    /// <summary>
    /// Deletes a cookie with specified name
    /// </summary>
    /// <param name="controller">extends the controller</param>
    /// <param name="cookieName">cookie name</param>
    public static void DeleteCookie(this Controller controller, string cookieName)
    {
        if (controller.HttpContext.Request.Cookies[cookieName] == null)
                return; //cookie doesn't exist
    
        var c = new HttpCookie(cookieName)
                    {
                        Expires = DateTime.Now.AddDays(-1)
                    };
        controller.HttpContext.Response.Cookies.Add(c);
    }
    
    0 讨论(0)
  • 2020-11-29 03:26

    You're close. You'll need to use the Response object to write back to the browser:

    if ( Request.Cookies["MyCookie"] != null )
    {
        var c = new HttpCookie( "MyCookie" );
        c.Expires = DateTime.Now.AddDays( -1 );
        Response.Cookies.Add( c );
    }
    

    More information on MSDN, How to: Delete a Cookie.

    0 讨论(0)
提交回复
热议问题