Remove and delete all cookies of my ASP NET c-sharp application

11,434

Actually, there is no way to do this correctly.

Consider the following code:

foreach (string key in Request.Cookies.AllKeys)
{
   HttpCookie c = Request.Cookies[key];
   c.Expires = DateTime.Now.AddMonths(-1);
   Response.AppendCookie(c);
}

This will work, but only if all cookies are set on root path, aka /. If the cookie is set to a virtual directory, it won't work, because the cookie's path does NOT get sent along with the cookie. A cookie only sends the name and the value, and nothing else, that is to say, no path.

So if you want to delete the cookies on the server with the above method, it will fail to delete all cookies that have, for example, path /Kamikatze/

So a more correct variant would be:

Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

    context.Response.ContentType = "text/plain"
    context.Response.Write("Die folgenden Cookies wurden gelöscht: ")

    If context.Session IsNot Nothing Then
        context.Session.Clear()
        context.Session.Abandon()
    End If

    For Each key As String In context.Request.Cookies.AllKeys
        context.Response.Write(key)
        context.Response.Write(System.Environment.NewLine)

        Dim c As HttpCookie = context.Request.Cookies(key)
        ' Here, the proc2-cookie is set on the VirtualPath ... '
        ' You need to handle all non-root cookies here, with if or switch or dictionary ' 
        If "proc2".Equals(key, StringComparison.InvariantCultureIgnoreCase) Then
            c.Path = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "/"
        End If

        ' For Set-Cookie without domain attribute, 
        ' the cookie's domain value is "the origin server".
        ' treat an absent Domain attribute as if the Domain attribute 
        ' were present And contained the current host name
        ' c.Domain = context.Request.Url.Host
        c.Expires = System.DateTime.UtcNow.AddMonths(-1)
        context.Response.Cookies.Set(c)
    Next key

    ' clear cookies server side
    context.Request.Cookies.Clear()
End Sub

See also Is it possible to get a stored cookie's path? and MDN Set-Cookie.

Share:
11,434
Antonio Mailtraq
Author by

Antonio Mailtraq

ASP.NET developer, SQL Consultant

Updated on June 04, 2022

Comments

  • Antonio Mailtraq
    Antonio Mailtraq almost 2 years

    I need remove and delete all cookies of my ASP NET c-sharp application after sent on message email.

    I have tried this solution without success because I have this error.

    Server cannot modify cookies after HTTP headers have been sent.
    

    In this line:

    HttpContext.Current.Response.Cookies.Add(expiredCookie);
    

    The message email started regularly.

    The google search does not help me.

    Anybody know how can I resolve do this?

    Can you suggest?

    Can you help me?

    My code below.

    Thank you in advance.

    private void ExpireAllCookies()
    {
        if (HttpContext.Current != null)
        {
            int cookieCount = HttpContext.Current.Request.Cookies.Count;
            for (var i = 0; i < cookieCount; i++)
            {
                var cookie = HttpContext.Current.Request.Cookies[i];
                if (cookie != null)
                {
                    var cookieName = cookie.Name;
                    var expiredCookie = new HttpCookie(cookieName) { Expires = DateTime.Now.AddDays(-1) };
                    HttpContext.Current.Response.Cookies.Add(expiredCookie);
                }
            }
    
            HttpContext.Current.Request.Cookies.Clear();
        }
    }
    
    
    
    ............
    
        {
            smtpClient.Send(mailMessagePlainText);
            ExpireAllCookies();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Ok.');window.location='http://...';", true);
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    
  • Antonio Mailtraq
    Antonio Mailtraq almost 9 years
    thank you, with your suggestion the cookies is not removed