views:

398

answers:

1

I have written this utility class to save and retrieve HttpCookies.

It seems not to be working, i.e. Cookie is not being retrieved...

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;
        }
    }

Can anyone tell me what can be the problem?

+3  A: 

I think your "Response" should be "Request" in the GetCookieValue function

jkelley
Changing Response to Request is giving null reference Exception.
Make sure the Request cookie collection contains that key first...if it doesn't have the key, then the cookie accessed by the key will be null, so getting its value will yield a null pointer exception
jkelley
Also, it may be helpful to put it in debug mode and set a watch on the cookie to dig into how your assigned values are stored.
jkelley
Any luck after making those changes? If the data isn't appearing in your debug console, try using a tool like HTTPWatch to look at the actual cookie data flowing back and forth when you make the request to make sure that the cookie is actually being allowed in your test environment.
jkelley
Yes. I have fixed it.