2

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
  • 1,397
  • 5
  • 34
  • 82
  • 1
    For the error message you are getting here is a good explanation http://stackoverflow.com/questions/5507580/server-cannot-modify-cookies-after-http-headers-have-been-sent – shreesha Aug 05 '15 at 14:20

2 Answers2

2

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.

Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
-1

You can try something like this

if (Request.Cookies["id"] != null)
{
    Response.Cookies["id"].Expires = DateTime.Now.AddDays(-1);   
}

or something like this

Session.Abandon();

Abandon() will only clear the session cookie but not the cookies you set manually. If your specified cookie doesn't exist it will simply return null.

Huang Chen
  • 1,177
  • 9
  • 24