【问题标题】:Not able to delete the cookies on logout无法在注销时删除 cookie
【发布时间】:2015-03-12 15:06:30
【问题描述】:

//接口--注入控制器

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

【问题讨论】:

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


    【解决方案1】:

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

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

    你也可以使用

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

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

    欲了解更多信息,请访问

    MSDN Cookie Help

    【讨论】:

      【解决方案2】:

      如果你使用登录用户

      SignInManager.PasswordSignInAsync(...)
      

      你可以试试

      AuthenticationManager.SignOut();
      

      而不是

      _context.Response.Cookies.Clear();
      

      【讨论】:

        猜你喜欢
        • 2012-10-01
        • 2016-06-03
        • 1970-01-01
        • 2013-10-26
        • 1970-01-01
        • 2019-03-16
        • 2021-07-07
        • 2012-10-16
        • 1970-01-01
        相关资源
        最近更新 更多