问题
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);
}
回答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.
回答2:
The code below works for me
foreach (string key in Request.Cookies.AllKeys)
{
HttpCookie c = Request.Cookies[key];
c.Expires = DateTime.Now.AddMonths(-1);
Response.AppendCookie(c);
}
来源:https://stackoverflow.com/questions/31833109/remove-and-delete-all-cookies-of-my-asp-net-c-sharp-application