LearnFast.Ninja

C# ASP.NET delete cookie

This tutorial is a little tricky because we do not have a delete function. We Use a request cookies to check if the cookie is not null. Then use response cookies expires to set a previous date. It is importent to check if the cookie is not null so the expires statement will be compile.

Main idea: Give the cookie an expired date.

Step 1: First check if the cookie is not empty. 

Step 2: Set the expires to be expired date by using datetime now and add negative number for days.

Working example code:

if (HttpContext.Current.Request.Cookies["cart"] != null)

{

    HttpContext.Current.Response.Cookies["cart"].Expires = DateTime.Now.AddDays(-1);

}


Tags

asp.net

cookie cookies delete datetime