注销时无法删除cookie

时间:2015-01-14 12:20:06

标签: c# asp.net-mvc asp.net-mvc-4 cookies logout

//界面 - 注入控制器

  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,login);

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

2 个答案:

答案 0 :(得分:1)

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

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

或者你可以使用

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

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

欲了解更多信息,请访问

MSDN Cookie Help

答案 1 :(得分:0)

如果要记录用户,请使用

SignInManager.PasswordSignInAsync(...)

你可以尝试

AuthenticationManager.SignOut();

而不是

_context.Response.Cookies.Clear();