user3007875
user3007875

Reputation: 153

ASP.NET cookie does not expire

I'm trying cookies for the first time in ASP. The problem is, the cookie doesn't expire no matter how many ways I write the code.

Making a cookie:

HttpCookie cookie = new HttpCookie("test");
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);

Checking if it exists:

if (Request.Cookies["test"] != null)
    Response.Write("test");
else
    Response.Write("no test");

It always shows "test".

Upvotes: 0

Views: 914

Answers (2)

Dinesh Nisshanka
Dinesh Nisshanka

Reputation: 61

You have destry all cookies in client side..
https://learn.microsoft.com/en-us/dotnet/api/system.net.cookie.expired?view=net-6.0 use this code it works for me.

<script>
    $(document).ready(function () {
        var cookies = document.cookie.split(";");

        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i];
            var eqPos = cookie.indexOf("=");
            var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
            document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
        }
    });
</script>

Remarks:
Expired cookies, if received, should be destroyed by the client application.

Upvotes: 0

Anders Abel
Anders Abel

Reputation: 69250

Are you doing this in the same request? In that case the old cookie is still present in the request, but will not be in subsequent requests.

Upvotes: 4

Related Questions