mvc 5不会删除cookie

时间:2015-06-23 15:49:59

标签: cookies asp.net-mvc-5

我正在尝试从响应者中删除所有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。我该如何解决?

2 个答案:

答案 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之后,它就完成了这个技巧

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();
            }