Clear all cookies in Asp.net Core

25,387

Solution 1

Request.Cookies is a key-value collection where the Key is a cookie name. So

foreach (var cookie in Request.Cookies.Keys)
{
    Response.Cookies.Delete(cookie);
}

See:

public abstract class HttpRequest
{
    // Summary:
    //     /// Gets the collection of Cookies for this request. ///
    //
    // Returns:
    //     The collection of Cookies for this request.
    public abstract IRequestCookieCollection Cookies { get; set; }
    ...
 }

and IRequestCookieCollection is

public interface IRequestCookieCollection : IEnumerable<KeyValuePair<string, string>>, IEnumerable

Solution 2

Try this:

//ASP.NET Core
foreach (string cookie in myCookies)
{
  Response.Cookies.Delete(cookie);  
}
Share:
25,387
Mohammad Daliri
Author by

Mohammad Daliri

My name is Mohammad Daliri.I'm from Iran

Updated on July 09, 2022

Comments

  • Mohammad Daliri
    Mohammad Daliri almost 2 years

    I'm working on a Asp.net Core website , and in my logout link I want to remove all current domain cookies. when I was work with Asp.net MVC I tried this code

    string[] myCookies = Request.Cookies.AllKeys;
    foreach (string cookie in myCookies)
    {
      Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
    }
    

    this code doesn't work in Asp.net Core. How can I clear all cookies in Asp.net Core?