ASP.NET HttpCookie助手类

时间:2009-08-03 14:50:42

标签: asp.net cookies

我已编写此实用程序类来保存和检索HttpCookies。

似乎没有工作,即没有检索到Cookie ...

public class AspNetUtil
    {
        private Page _page = null;

        public AspNetUtil(Page page)
        {
            _page = page;
        }

        public bool SaveInCookie(string cookieName, string valueKey, string valueToBeStored, int expiryTimeInMinutes)
        {
            bool success = false;

            try
            {
                HttpCookie cookie = null;

                if(_page.Request.Cookies[cookieName] == null)
                {
                    cookie = new HttpCookie(cookieName);
                }
                else
                {
                    cookie = _page.Request.Cookies[cookieName];
                }

                cookie.Values.Add(valueKey, valueToBeStored);

                cookie.Expires = DateTime.Now.AddMinutes(expiryTimeInMinutes);

                _page.Response.Cookies.Add(cookie);
            }
            catch(Exception ex)
            {
                success = false;

                throw ex;
            }

            return success;
        }

        public string GetCookieValue(string cookieName, string valueKey)
        {
            string cookieValue = string.Empty;

            try
            {
                cookieValue = (string)_page.Response.Cookies[cookieName].Values[valueKey];
            }
            catch (Exception ex)
            {
                cookieValue = string.Empty;
                throw ex;
            }

            return cookieValue;
        }
    }

谁能告诉我可能出现什么问题?

1 个答案:

答案 0 :(得分:5)

我认为您的“响应”应该是GetCookieValue函数中的“Request”