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?
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();
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.
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.
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.
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
Try this:
//ASP.NET Core
foreach (string cookie in myCookies)
{
Response.Cookies.Delete(cookie);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With