无法在注销时删除 cookie

Not able to delete the cookies on logout

//接口--注入controller

  public interface IContext
{
    HttpRequestBase Request { get; }
    HttpResponseBase Response { get; }
}

//实现

  public class Context : IContext
{
    public HttpRequestBase Request { get { return new HttpRequestWrapper(HttpContext.Current.Request); } }
    public HttpResponseBase Response { get { return new HttpResponseWrapper(HttpContext.Current.Response); } }
}

//登录时设置Cookie。 SetCookie(_context, 登录);

public void SetCookie(IContext context, Login login)
{
        var loginDetails = new JavaScriptSerializer().Serialize(login);
        var cokie = new HttpCookie("login", login);
        context.Response.Cookies.Add(cokie);
}

//正在尝试注销。

    public ActionResult Logout()
    {
        foreach (var key in _context.Request.Cookies.AllKeys)
        {
            try
            {
                _context.Response.Cookies.Remove(key); //this didn't work

                //tried this even this is not working
                var login = new Login {Identity = "", LogIn = false};
                _login.SetCookie(_context, login);
            }
            catch (Exception e)
            {
            }
        }
        _context.Response.Cookies.Clear(); //this didn't work either

        return RedirectToAction("Index", "Login");
    }

在登录索引上,当我检查当前登录 cookie 值时,它始终具有登录用户的值,只是没有设置为 null 或空。 我怀疑 IContext 的实现有问题。上面应该有一个 setter 吗?不确定..

也尝试过:

        var cokie = context.Request.Cookies["login"];
        cokie.Expires = DateTime.Now.AddDays(-2);
        cokie.Value = null;
        context.Response.Cookies.Add(cokie);

如果要登录用户,请使用

SignInManager.PasswordSignInAsync(...)

你可以试试

AuthenticationManager.SignOut();

而不是

_context.Response.Cookies.Clear();

如果您使用表单身份验证,则可以使用以下代码。它将清除所有必需的 cookie

FormsAuthentication.SignOut();
Session.Abandon();

或者您可以使用

Session.Abandon();
Response.Cookies.Clear();

YourCookies.Expires = DateTime.Now.AddDays(-1d);

更多信息请访问

MSDN Cookie Help