Asp.net How To Remove Cookie

Asp.net How To Remove Cookie How to remove cookie in asp.net.

Do you want to remove or delete cookie using Asp.net? Here is a trick about how we can remove cookie from client. Cookies get stored at browser. You can’t delete them using Asp.net code. However the trick is, set expiration date before today’s date can tell browser to remove cookie. Let’s see example in Asp.net with C#.net and VB.net.

C#.net code to remove cookie.

1. First we need to detect whether cookie exists in request or not.

2. If cookie exists, set it’s expiration date to past.

3. Add new expiration date to cookie in response.

public partial class Demo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["username"] != null)
{
HttpCookie cookie = new HttpCookie("username");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}

}
}

VB.net Remove Cookie.

In Asp.net with Vb.net you can remove cookie at client side by adding expiration date prior to today's date. As I have already mentioned, you can't delete the cookie directly. It's browser responsibility to delete cookie.

Public Partial Class Demo
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Request.Cookies("username") IsNot Nothing Then
Dim cookie As New HttpCookie("username")
cookie.Expires = DateTime.Now.AddDays(-1)
Response.Cookies.Add(cookie)
End If

End Sub
End Class

You can set cookies for domain or specific to page. To set page specific cookie, use Path properties of HttpCookie instance.

Tags:

Asp.net How To Write a Cookie and ReadAsp.net page specific cookieAsp.net How To Expire a CookieRemove internet explorer[C#] Remove Last Character From StringASp.net 2.0 step by step Membership Provider asp net image uploadAsp.net Interview Questions for 2 years or 3 years experiancehow to remove Google ChromeJQuery add/remove Class DynamicallyRemove net framework 40

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.