Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 578
Mohammad Daliri Avatar asked Aug 07 '17 06:08

Mohammad Daliri


People also ask

How do I delete cookies in net core?

When the Remove Cookie Button is clicked, DeleteCookie Action method is executed which removes the Cookie from Request. Cookies collection using the Delete method. //Set the Expiry date of the Cookie. CookieOptions option = new CookieOptions();

What is cookies in asp net core?

Cookies are represented as key-value pairs, and you can take advantage of the keys to read, write, or delete cookies. ASP.NET Core uses cookies to maintain session state; the cookie that contains the session ID is sent to the client with each request.

How do I clear cookies after logging out?

You cannot directly delete a cookie on a user's computer. However, you can direct the user's browser to delete the cookie by setting the cookie's expiration date to a past date.

What is cookies in asp net c#?

A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.


2 Answers

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
like image 111
Set Avatar answered Sep 28 '22 04:09

Set


Try this:

//ASP.NET Core
foreach (string cookie in myCookies)
{
  Response.Cookies.Delete(cookie);  
}
like image 21
ahmad-r Avatar answered Sep 28 '22 06:09

ahmad-r