Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/ASP.NET: can't remove cookies with Domain property specified

I have the following code in my login method:

Response.Cookies["cookie"].Value = "...";
Response.Cookies["cookie"].Domain = "domain.com";

This way the cookie is put into the main domain and all subdomains

However when I try to remove the cookies:

Response.Cookies["cookie"].Expires = DateTime.Now.AddYears(-1);

It doesn't work!

When I remove the 2 line of code where Domain property is specified, it works fine.

How can I solve this problem?

Thanks

like image 429
Alex Avatar asked Aug 09 '11 09:08

Alex


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C in C?

Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'. So ++ being the increment operator, C has an incremented version called as “C++”.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Why is C language popular?

It is fast The programs that you write in C compile and execute much faster than those written in other languages. This is because it does not have garbage collection and other such additional processing overheads. Hence, the language is faster as compared to most other programming languages.


2 Answers

Okay, I figured that out.

When you remove a cookie with Domain property set, you need to set the very same property for the new fake cookie:

if (Request.Cookies["cookie"] != null)
{
    HttpCookie myCookie = new HttpCookie("cookie");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    myCookie.Domain = "domain.com"; // !!!!
    Response.Cookies.Add(myCookie);
}
like image 171
Alex Avatar answered Nov 10 '22 00:11

Alex


I suspect you are setting Expires while the Response is on a subdomain...
Crosscheck: Can you try and set it from the domain itself and see if that works ?

According to http://msdn.microsoft.com/en-us/library/ms178195%28v=VS.100%29.aspx you can delete a cookie by:

if (Request.Cookies["cookie"] != null)
{
    HttpCookie myCookie = new HttpCookie("cookie");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}
like image 32
Yahia Avatar answered Nov 10 '22 01:11

Yahia