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

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.


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.


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);
}

Comments

  1. Azrael

    • 2019/1/5

    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 

  2. Kingsley

    • 2019/7/21

    Session.Clear (); HttpCookie c = Request.Cookies ["MyCookie"]; if (c != null) { c = new HttpCookie ("MyCookie"); c ["AT"] = null; c.Expires = DateTime.Now.AddDays (-1); Request.Cookies.Add (c); } return RedirectToAction ("Index", "Home"); When the redirect happens, it finds the cookie again and moves on as though I never logged out.

  3. Berisha

    • 2015/6/15

    possible duplicate of How do you clear cookies using asp.net mvc 3 and c#?. – Jakub Konecki · 1 · Yes, I want to clear all cookies, not just one, 

  4. Valentino

    • 2019/5/15

    Session.Clear (); HttpCookie c = Request.Cookies ["MyCookie"]; if (c != null) { c = new HttpCookie ("MyCookie"); c ["AT"] = null; c.Expires = DateTime.Now.AddDays (-1); Request.Cookies.Add (c); } return RedirectToAction ("Index", "Home"); When the redirect happens, it finds the cookie again and moves on as though I never logged out.

  5. Rowen

    • 2017/2/9

    A brief tutorial illustrating how to manage Cookies in ASP.NET Web Forms, MVC and Core with examples of code in C Sharp language.

  6. Holden

    • 2019/3/10

    Dealing with Cookies has been a typical requirement of most web developers since the early days of the World Wide Web. In this article, after a brief introduction to explain how Cookies work in a typical web application, we will present some helper classes that allow you to implement the main activities necessary to manage Cookies in any ASP.NET project – Web Forms, MVC, and/or Core – in a

  7. Ferri

    • 2021/1/17

    But when a user delete it by clicking on the button, Cookies do not delete. /5122404/how-do-you-clear-cookies-using-asp-net-mvc-3-and-c.

  8. Ishaan

    • 2018/12/20

    When the Remove Cookie Button is clicked, the respective Button event handler is executed which fetches the Cookie object from the Request.Cookies collection using its Key. A Cookie cannot be removed or deleted, it only can be made expired and hence the Expiry Date of the Cookie is set to a past date and the Cookie is updated back into the Response.Cookies collection.

  9. Pablo

    • 2020/9/23

    You created a cookie on you asp.net forms application now you would like to delete it. This quick article show how to do the trick 3 October 2010.

  10. Russell

    • 2015/3/28

    You cannot delete cookies via ASP.Net. This is something that is browser dependent and cannot be done directly. The best you can do is expire cookies for your website / session.

  11. Aayan

    • 2016/4/28

    You cannot delete cookies via ASP.Net. This is something that is browser dependent and cannot be done directly.

  12. Adrien

    • 2021/1/5

    In fact Response cookies are empty and request cookie contains the cookie I want to delete when the following commands are executed it no longer contains the cookie I deleted but in browser the cookie still exists and I am able to do things that authorized users can even after signing out.

  13. Adonis

    • 2016/3/24

    Итак, я действительно думаю, что делаю это правильно, но файлы cookie не очищаются. Session.Clear(); HttpCookie c = Request.Cookies["MyCookie"]; if (c 

  14. Callahan

    • 2018/2/5

    ResultLabel.ForeColor = Color.Red; UserNameTextBox.Focus(); } } protected void DeleteButtonClick(object sender, EventArgs e) { if (Request.Cookies["UserName"] != null) { Response.Cookies["UserName"].Value = ""; Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1); } else { ResultLabel.Text = "No Cookie is present!";

  15. Ameer

    • 2021/2/17

    Ok, donc je pense vraiment que je fais ça correctement, mais les cookies ne sont pas effacés. Session.Clear(); HttpCookie c = Request.Cookies["MyCookie"] 

  16. Augustus

    • 2017/1/31

    Ok, realmente creo que estoy haciendo esto bien, pero las cookies no se están borrando. Session.Clear(); HttpCookie c = Request.Cookies["MyCookie"]; if (c !

Comments are closed.

Recent Posts