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

前端 未结 3 893
攒了一身酷
攒了一身酷 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: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.

    /// 
    /// Deletes a cookie with specified name
    /// 
    /// extends the controller
    /// cookie name
    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);
    }
    

提交回复
热议问题