【问题标题】:How to delete cookies when browser is closed? ASP.Net core,C#浏览器关闭时如何删除cookies? ASP.Net 核心,C#
【发布时间】:2020-06-18 00:46:30
【问题描述】:

当我的浏览器在我的 ASP.NET Core MVC 项目中关闭时,我需要删除 cookie 这包括我用来创建 cookie 的代码。

      var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name,user.email),
                    new Claim(ClaimTypes.Role,user.roles)
                };
                    var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    var princilple = new ClaimsPrincipal(identity);
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, princilple);

                        if (User.IsInRole("Admin"))
                        {
                            return RedirectToAction("Dashboard", "Home", new { user.id });

                        }
                        else
                        {
                            return RedirectToAction("Details", "Home", new { user.id });
                        }


                }
                else
                {
                    TempData["Message"] = "Invalid Username/Password";
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                return RedirectToAction("Error", "Home");
            }

【问题讨论】:

  • 你可以在 unload 事件之前使用 js 和 window 来移除它,但是如果你只是想让 cookie 在浏览期间持续存在,为什么不使用 session 来代替呢?
  • 如果您只想要 Session 级别的授权,为什么还要使用 cookie?

标签: javascript c# jquery cookies asp.net-core-mvc


【解决方案1】:

你可以试试这个。

$(window).unload(function() {
   $.cookies.del('myCookie');
});

【讨论】:

  • HttpOnly cookie 怎么样?
【解决方案2】:

您正在使用 SignInAsync 创建 cookie 而不将 IsPersistent 设置为 true ,它会给您一个会话 cookie,当您关闭浏览器窗口时它会消失,您不需要自己控制它,请详情请参考document

【讨论】:

  • 会话 cookie 是事实上的 cookie 方法(多年来),仅在浏览器打开 (fsvo) 时持续存在。
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
  • 2014-01-26
  • 1970-01-01
  • 2012-12-02
相关资源
最近更新 更多