Check if Cookie Exists

后端 未结 7 576
失恋的感觉
失恋的感觉 2020-12-03 02:21

From a quick search on Stack Overflow I saw people suggesting the following way of checking if a cookie exists:

HttpContext.Current.Response.Cookies         


        
7条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 03:04

    public static class CookieHelper
    {
        /// 
        /// Checks whether a cookie exists.
        /// 
        /// A CookieCollection, such as Response.Cookies.
        /// The cookie name to delete.
        /// A bool indicating whether a cookie exists.
        public static bool Exists(this HttpCookieCollection cookieCollection, string name)
        {
            if (cookieCollection == null)
            {
                throw new ArgumentNullException("cookieCollection");
            }
    
            return cookieCollection[name] != null;
        }
    }
    

    Usage:

    Request.Cookies.Exists("MyCookie")
    

提交回复
热议问题