0

Using MVC

I am creating a cookie on login like the following:

Response.Cookies.Add(New HttpCookie("UserId", Id))

I searched for ways to delete cookies so I can use it on Logout, and I found this:

 If Response.Cookies("UserId") IsNot Nothing Then
                Dim c = New HttpCookie("UserId")
                c.Expires = DateTime.Now.AddDays(-1)
                Response.Cookies.Add(c)
 End If

 Response.Cookies.Clear()

And on Client side I am doing the following:

 document.cookie = "access_token=";

But I figured out this doesn't delete the cookie, it just empties it, I would still have a cookie called UserId with a value of Nothing.

Now if the user Logs out and logs in right after it, it's causing me problems.

What I want to do, is completely delete the Cookie with the name UserId , Completely erase it from the browser cookies, not just empty its value.

Is there any way to do that?

Edit

I think the problem is with this part:

If Response.Cookies("UserId") IsNot Nothing Then
                    Dim c = New HttpCookie("UserId")

Because when I debug this code, after this line, The count of Response.Cookies I get is 2 , means it's creating 2 cookies with the same name and getting confused.

HelpASisterOut
  • 3,085
  • 16
  • 45
  • 89

2 Answers2

0

you missed expires, for example:

document.cookie="access_token=; expires=Thu, 18 Dec 2013 12:00:00 UTC";
wasikuss
  • 969
  • 8
  • 13
  • Can't I just set document.cookie=""; in Javascript? Wouldnt that delete the cookie and not just its value? – HelpASisterOut Mar 13 '15 at 08:06
  • document.cookie acts as property with getter and setter. When you read, it returns all cookies. When you write it create or modify cookie. Passing empty string will do nothing. – wasikuss Mar 14 '15 at 12:00
0

You can Use

ControllerContext.HttpContext.Response.Cookies.Remove("cookie name")

But you cannot directly delete a cookie, you have to set it to expire before the current date like an example:

 myCookie.Expires = DateTime.Now.AddDays(-1d);
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47