gpt4 book ai didi

asp.net-mvc - Cookie 未删除

转载 作者:行者123 更新时间:2023-12-02 04:53:01 25 4
gpt4 key购买 nike

我使用以下代码在我的 asp.net mvc(C#) 应用程序中设置 cookie:

public static void SetValue(string key, string value, DateTime expires)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;

HttpCookie cookie = new HttpCookie(key, value) { Expires = expires };
_response.Cookies.Set(cookie);
}

当用户单击注销时,我需要删除 cookie。设置的 cookie 不会通过清除/删除来删除/删除。代码如下:

public static void Clear()
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;

_request.Cookies.Clear();
_response.Cookies.Clear();
}

public static void Remove(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;

if (_request.Cookies[key] != null)
{
_request.Cookies.Remove(key);
}
if (_response.Cookies[key] != null)
{
_response.Cookies.Remove(key);
}
}

我已经尝试了上述两个功能,但当我尝试检查是否存在时,cookie仍然存在。

public static bool Exists(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
return _request.Cookies[key] != null;
}

这里可能有什么问题?或者我需要做什么来删除/删除 cookie?

最佳答案

清除响应的 cookie 并不指示浏览器清除 cookie,它只是不将 cookie 发送回浏览器。要指示浏览器清除 cookie,您需要告诉它 cookie 已过期,例如

public static void Clear(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_response = httpContext.Response;

HttpCookie cookie = new HttpCookie(key)
{
Expires = DateTime.Now.AddDays(-1) // or any other time in the past
};
_response.Cookies.Set(cookie);
}

关于asp.net-mvc - Cookie 未删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1771165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com