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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – Cookie不会被删除前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用以下代码在我的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);
}
原文链接:https://www.f2er.com/aspnet/254260.html

猜你在找的asp.Net相关文章