加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – Cookie不会被删除

发布时间:2020-12-15 19:04:16 所属栏目:asp.Net 来源:网络整理
导读:我使用以下代码在我的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 =
我使用以下代码在我的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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读