删除.net Core 2.0中的Cookie

编程入门 行业动态 更新时间:2024-10-26 02:35:38
本文介绍了删除 Core 2.0中的Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在研究.Net Core 2.0 MVC Web应用程序。需要操纵身份验证cookie,以根据用户角色设置过期时间跨度。过期时间过后,如果没有活动,则用户将退出应用程序。为此,我创建了一个过滤器,该过滤器在用户每次与站点交互时都会被调用。在该过滤器中,我基本上是在读取cookie值,将其存储在temp变量中,删除现有的cookie,然后将具有相同键和值的新cookie附加到响应中。

I am working on .Net Core 2.0 MVC Web Application. There is a need to manipulate authentication cookie to set expire time span based on user role. After the expire time span, the user will be logged out of the application if there is no activity. In order to that, I created a Filter which is being called everytime user interacts with the site. In that filter, I am basically reading cookie value, store it in the temp variable, delete existing cookie, and append new cookie with same key and value to the response.

var cookieContent = Request.Cookie[key]; Response.Cookies.Delete(key); Response.Cookies.Append(new cookie with same name and value);

我能够创建具有所需过期时间的新cookie,并且确实可以正常工作。 我的问题是, Response.Cookies.Delete(key); 并没有真正删除cookie。

I am able to create a new cookie with required expire time, and it does work fine. My problem here is, Response.Cookies.Delete(key); doesn't really delete the cookie.

Microsoft文档说,我们无法从用户电脑因此,有什么方法可以从硬盘驱动器中删除Cookie吗?如果不是, Response.Cookies.Delete(cookie); 会做什么?

Microsoft documentation says we cannot delete the cookie from the user's pc. so is there any way to delete the cookie from hard-drive? If not, what does Response.Cookies.Delete(cookie); do?

推荐答案

在ASP.NET Core中,您可以/应该使用以下方法:

In ASP.NET Core, you can/should use the following method:

private void DeleteCookies() { foreach (var cookie in HttpContext.Request.Cookies) { Response.Cookies.Delete(cookie.Key); } }

内部执行的操作是发送 Set-Cookie Http Response Header中的'指令,指示浏览器使cookie过期并清除其值。

What this does internally is to send 'Set-Cookie' directives in the Http Response Header to instruct the browser to both expire the cookie and clear its value.

  • ResponseCookies.Delete方法
  • MSDN此处的文档- IResponseCookies.Delete方法
  • ASP.NET Core source code for ResponseCookies.Delete Method
  • MSDN docs here - IResponseCookies.Delete Method

示例响应标头:

HTTP/1.1 302 Found Cache-Control: no-cache Pragma: no-cache Expires: Thu, 01 Jan 1970 00:00:00 GMT Server: Microsoft-IIS/10.0 Set-Cookie: Cookie1=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; secure; samesite=lax Set-Cookie: Cookie2=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; secure; samesite=lax Set-Cookie: Cookie3=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; secure; samesite=lax

更多推荐

删除.net Core 2.0中的Cookie

本文发布于:2023-11-08 11:03:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569197.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Core   net   Cookie

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!