删除.net Core 2.0中的Cookie [英] Delete cookies in .net core 2.0

查看:491
本文介绍了删除.net 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.

  • 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆