Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all current domain cookies in MVC website?

Tags:

asp.net-mvc

I am working on a MVC website, and in my logout link I want to remove all the current domain cookies.

I tried this:

this.ControllerContext.HttpContext.Response.Cookies.Clear();

and this:

Response.Cookies.Clear();

but both didn't work and the cookies still there.

like image 776
Amr Elgarhy Avatar asked Jun 19 '11 17:06

Amr Elgarhy


People also ask

How do I clear a cookie in C#?

Add(new HttpCookie("ASP. NET_SessionId", "")); This code example clears the session state from the server and sets the session state cookie to null. The null value effectively clears the cookie from the browser.

How does MVC application get cookies from client?

In ASP.Net MVC application, a Cookie is created by sending the Cookie to Browser through Response collection (Response. Cookies) while the Cookie is accessed (read) from the Browser using the Request collection (Request.

What is Cookies in ASP NET MVC?

Cookies are small files that are created in the web browser's memory (if they're temporary) or on the client's hard drive (if they're permanent). CookiesExample.zip. Cookies are one of the State Management techniques, so that we can store information for later use.

What is cookies C#?

What are cookies in C#? Cookies are small units of information that follow all request processes and web pages as they travel between Web browsers and servers. The above definition implies that every web page opened on a website has an exchange of cookies between the server and the web pages.


2 Answers

How about this?

string[] myCookies = Request.Cookies.AllKeys;
foreach (string cookie in myCookies)
{
  Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
}
like image 159
Swift Avatar answered Oct 17 '22 16:10

Swift


What about this ?

    if (Request.Cookies["cookie"] != null)
    {
        HttpCookie myCookie = new HttpCookie("cookie");
        myCookie.Expires = DateTime.Now.AddDays(-1d);
        Response.Cookies.Remove(myCookie);
    }
like image 1
Sunil Acharya Avatar answered Oct 17 '22 15:10

Sunil Acharya