无法使用 .net Core 中的 Response.Cookies 方法访问 cookie

Cannot reach the cookies with Response.Cookies method in .net Core

我有一个带有 .net 核心和 reactjs 的项目。我可以成功创建 cookie,但在我的注销方法中,我无法使用 response.cookies 方法获取 cookie 以删除 cookie。我想要的只是删除 cookie。这是我的后端代码:

        [HttpPost]
        public async Task<IActionResult> Login(User user)
        {
            var userDb = await _creditTrackerContext.Users.FirstOrDefaultAsync(x => x.UserName == user.UserName && x.Password == user.Password);

            if (userDb is not null && user.UserName == userDb.UserName && user.Password == userDb.Password)
            {
                var jwt = _jwtService.Generate(userDb.Id);

                Response.Cookies.Append("jwt", jwt, new CookieOptions
                {
                    HttpOnly = true,
                    IsEssential = true,
                    SameSite = SameSiteMode.None,
                    Secure = true,
                });

                return Ok(new
                {
                    message = "success"
                });
            }
            return BadRequest(new { message = "Invalid Credentials" });
        }

        [HttpGet]
        public async Task<IActionResult> getAuthenticatedUser()
        {
            try
            {
                var jwt = Request.Cookies["jwt"];

                var token = _jwtService.Verify(jwt);

                int ID = Convert.ToInt32(token.Issuer);

                var user = await _creditTrackerContext.Users.FindAsync(ID);
                return Ok(user);
            }
            catch (Exception _ex)
            {
                return Unauthorized(_ex);
            }
        }

        [Route("Logout")]
        [HttpPost()]
        public IActionResult Logout()
        {
            try
            {
                Response.Cookies.Delete("jwt");

                return Ok(new
                {
                    message = "success logout"
                });
            }
            catch (Exception _ex)
            {

                throw new Exception("",_ex);
            }
            
        } 

这是我从前端发出的注销调用:

    console.log('test')
    const URL = 'https://localhost:44337/api/user/logout'
     fetch(URL,{
      method:'POST',
      headers:{'Content-Type':'application/json'},
      credentials:'include'
    }).then( setRedirect(true))
  } 

我还看到一些关于在非 public 成员中启用 cookie 解码属性的信息,但我没有兴趣。 提前致谢

您不能通过以下方式删除浏览器中的 cookie:

Response.Cookies.Delete("jwt");

相反,您需要创建一个具有相同名称但过期日期为过去的新 cookie。

像这样:

if (Request.Cookies["jwt"] != null)
{
    var c = new HttpCookie("jwt")
    {
        Expires = DateTime.Now.AddDays(-1)
    };
    Response.Cookies.Add(c);
}

但是,不加密地存储令牌不是一个好主意。我会将其添加到 ASP.NET 核心会话 cookie 中,因为这样我就知道数据在添加为 cookie 之前已正确加密。