无法在注销时删除 Cookie

本文关键字:删除 Cookie 注销 | 更新日期: 2023-09-27 18:37:25

//接口--注入控制器

  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的实现有问题。上面应该有一个二传手吗?不确定。。

还尝试过:

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

无法在注销时删除 Cookie

如果您使用的是窗体身份验证,则可以使用以下代码。它将清除所有必需的饼干

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

或者,您可以使用

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

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

欲了解更多信息,请访问

MSDN 饼干帮助

如果要登录用户,请使用

SignInManager.PasswordSignInAsync(...)

你可以试试

AuthenticationManager.SignOut();

而不是

_context.Response.Cookies.Clear();