Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I manually delete a cookie in asp.net MVC 4

Tags:

c#

asp.net-mvc

I need to delete authentication cookie manually (Instead of using FormsAuthentication.SignOut whcih for some reasons does not work). I tried

System.Web.HttpContext.Request.Cookies.Remove(cookieName); // for example .ASPXAUTH
System.Web.HttpContext.Response.Cookies.Remove(cookieName); // for example .ASPXAUTH
FormsAuthentication.SignOut(); // I don't know why this one does not work

Neither of those command work. In fact Response cookies are empty and request cookie contains the cookie I want to delete when the following commands are executed it no longer contains the cookie I deleted but in browser the cookie still exists and I am able to do things that authorized users can even after signing out.

like image 488
Dimitri Avatar asked Nov 26 '13 13:11

Dimitri


People also ask

How you can delete cookie in asp net?

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.

Where are ASP Net cookies stored?

Cookies is a small piece of information stored on the client machine. This file is located on client machines "C:\Document and Settings\Currently_Login user\Cookie" path. Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines.

How do I access cookies in asp net?

You may use Request. Cookies collection to read the cookies. Show activity on this post. HttpContext.

How do cookies work in ASP NET MVC?

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. Cookies).


2 Answers

Try:

if (Request.Cookies["MyCookie"] != null)
{
    var c = new HttpCookie("MyCookie")
    {
        Expires = DateTime.Now.AddDays(-1)
    };
    Response.Cookies.Add(c);
}

More information on MSDN.

like image 50
Mateusz Rogulski Avatar answered Oct 17 '22 19:10

Mateusz Rogulski


c.Expires = DateTime.Now.AddDays(-1); This does not clear cookies instantly.

Use this: c.Expires = DateTime.Now.AddSeconds(1); This will clear cookies instantly.

like image 3
JBash Avatar answered Oct 17 '22 19:10

JBash