我正在尝试从响应者中删除所有Cookie, 该功能在服务项目中。
代码:
int limit = HttpContext.Current.Request.Cookies.Count;
for (int i = 0; i < limit; i++)
{
cookieName = HttpContext.Current.Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Value = null;
aCookie.Expires = DateTime.Now.AddYears(-1);
HttpContext.Current.Response.Cookies.Add(aCookie)
}
但响应只会添加更多具有相同名称的Cookie。我该如何解决?
答案 0 :(得分:1)
试试这个:
string[] myCookies = Request.Cookies.AllKeys;
foreach (string cookie in myCookies)
{
Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
}
编辑:此建议基于与您将Cookie添加到响应中而不是更新已存在的cookie有关的猜测。
答案 1 :(得分:1)
cookie = new HttpCookie(CookieName, CustId);
以任何其他方式声明cookie并不起作用, 例如:
int limit = HttpContext.Current.Request.Cookies.Count;
for (int i = 0; i < limit; i++)
{
cookieName = HttpContext.Current.Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Value = null;
aCookie.Expires = DateTime.Now.AddYears(-1);
HttpContext.Current.Response.Cookies.Add(aCookie);
}
或
var cookie = HttpContext.Current.Response.Cookies[CookieName];
if(cookie == null)
{
cookie = new HttpCookie(CookieName, CustId);
}
else
{
cookie.Expires = DateTime.Now.AddDays(-100);
HttpContext.Current.Response.Cookies.Add(cookie);
//HttpContext.Current.Session.Clear();
}