清除Asp.net Core中的所有cookie

时间:2017-08-07 06:31:33

标签: asp.net-core

我正在Asp.net Core网站上工作,在我的退出链接中,我想删除所有当前的域Cookie。 当我与Asp.net MVC合作时,我尝试了这段代码

string[] myCookies = Request.Cookies.AllKeys;
foreach (string cookie in myCookies)
{
  Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
}

此代码在Asp.net Core中无效。 如何清除Asp.net Core中的所有cookie?

2 个答案:

答案 0 :(得分:14)

Request.Cookies是一个键值集合,其中Key是一个cookie名称。所以

foreach (var cookie in Request.Cookies.Keys)
{
    Response.Cookies.Delete(cookie);
}

请参阅:

public abstract class HttpRequest
{
    // Summary:
    //     /// Gets the collection of Cookies for this request. ///
    //
    // Returns:
    //     The collection of Cookies for this request.
    public abstract IRequestCookieCollection Cookies { get; set; }
    ...
 }

IRequestCookieCollection

public interface IRequestCookieCollection : IEnumerable<KeyValuePair<string, string>>, IEnumerable

答案 1 :(得分:1)

试试这个:

//ASP.NET Core
foreach (string cookie in myCookies)
{
  Response.Cookies.Delete(cookie);  
}