尝试删除两个具有相同名称的cookie

时间:2016-11-21 23:18:34

标签: asp.net asp.net-mvc cookies

框架/语言:ASP.NET MVC C#

问题:尝试删除两个名称相同但不同的HttpOnly Cookie。一个cookie在.somedomain.com上,另一个在www.somedomain.com上

详细说明:

下面列出了使这些cookie过期的功能。它只会到期一个cookie,最后一个 - 这似乎表明它被覆盖了。这是预期的吗?有解决方法吗?

private static void ExpireCookie(string cookieName)
{
    var context = HttpContext.Current;
    context.Response.Cookies.Remove(cookieName);
    var cookieValue = string.Empty;
    if (context.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
    var expirationTime = new DateTime(1999, 10, 12);
    var cookie = new HttpCookie(cookieName, cookieValue)
    {
        HttpOnly = true,
        Path = FormsAuthentication.FormsCookiePath,
        Expires = expirationTime,
        Secure = FormsAuthentication.RequireSSL,
        Domain = ".somedomain"
    };
    context.Response.Cookies.Add(cookie);
    //remove the cookieName on www.somedomain.com
     var cookie2 = new HttpCookie(cookieName, cookieValue)
    {
        HttpOnly = true,
        Path = FormsAuthentication.FormsCookiePath,
        Expires = expirationTime,
        Secure = FormsAuthentication.RequireSSL,
    };
    context.Response.Cookies.Add(cookie2);
 }

1 个答案:

答案 0 :(得分:0)

为了提供一些关闭,我最终做到了这一点:

  • 使用其他名称添加第二个,因此上面的cookie2将添加为

    var cookie2 = new HttpCookie(cookieName +"2", cookieValue)
    {
    HttpOnly = true,
    Path = FormsAuthentication.FormsCookiePath,
    Expires = expirationTime,
    Secure = FormsAuthentication.RequireSSL,
    };
    
  • 循环浏览所有Cookie并将cookieName + 2重命名为cookieName

    for (var i = 0; i < currentResponse.Cookies.Count; i++)
        {
            var currentResponseCookie = currentResponse.Cookies[i];
            if (currentResponseCookie != null && currentResponseCookie.Name == cookieName + "2")
            {
                currentResponse.Cookies[i].Name = cookieName;
                break;
            }
        }
    

很难过,但是能为我做好准备。