Search code examples
asp.net-corecookies

Clear all cookies in Asp.net Core


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?


Solution

  • 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