开发者

Converting from saving in Session to Cookies?

So, I am working on a demo web da开发者_运维问答shboard. Previously, I had been using Session to store settings about the dashboard, but I would like to move it to a more persistent means of saving settings.

It seems to me that using cookies would be my best bet. I'm not entirely positive I have the time to work everything out for writing to/from a database properly.

That being said, I might be in over my head on some assumptions I had made about the similarities between Session and Cookies.

Currently, I have some code like this:

public Dictionary<string, RadPageViewSetting> PageViewStates
    {
        get
        {
            Dictionary<string, RadPageViewSetting> _pageViewStates = (Dictionary<string, RadPageViewSetting>)Session["PageViewStates"];
            if (object.Equals(_pageViewStates, null))
            {
                _pageViewStates = new Dictionary<string, RadPageViewSetting>();
                Session["PageViewStates"] = _pageViewStates;
            }

            return _pageViewStates;
        }
        set
        {
            Session["PageViewStates"] = value;
        }
    }

where RadPageViewSetting is a class with some properties in it which I am recording.

Is this functionality possible with cookies? If not, where should I be looking to persist my data through browser-closes?

EDIT: I am going to use http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx to help me serialize the dictionary and then go about serializing my own custom data hypers (RadPageViewSetting).

EDIT: Here's my untested solution. Could someone take a look at this real quick and let me know if it looks incorrect?

        public SerializableDictionary<string, RadPageViewSetting> PageViewStates
    {
        get
        {
            SerializableDictionary<string, RadPageViewSetting> _pageViewStates = new SerializableDictionary<string,RadPageViewSetting>();
            HttpCookie cookie = HttpContext.Current.Response.Cookies["PageViewStates"]; //If the named cookie does not exist, this method creates a new cookie with that name.

            if (object.Equals(cookie, null))
            {
                cookie = new HttpCookie("PageViewStates");
                cookie.Expires = DateTime.Now.AddYears(100);
                cookie.Value = null;
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            else if( cookie.Value != null )
            {
                MemoryStream stream = new MemoryStream();
                StreamWriter writer = new StreamWriter(stream);
                writer.Write(cookie.Value);
                XmlSerializer serializer = new XmlSerializer(_pageViewStates.GetType());
                _pageViewStates = serializer.Deserialize(stream) as SerializableDictionary<string, RadPageViewSetting>;
                HttpContext.Current.Response.Cookies.Set(cookie);
            }

            return _pageViewStates;
        }
        set
        {
            XmlSerializer serializer = new XmlSerializer(value.GetType());
            MemoryStream stream = new MemoryStream();
            serializer.Serialize(stream, value);
            StreamReader reader = new StreamReader(stream);
            HttpContext.Current.Response.Cookies["PageViewStates"].Value = reader.ReadToEnd();
        }
    }


Simple use Response.Cookies instead of Session.

Basically in a nutshell from MSDN




Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

You should be able to store what ever you like in the cookie as long as you can serialize it into a string. As cookies are plain text.


While the answer you accepted technically works, I think it might be easier to just set two attribute values in the sessionState element of your web.confg.

To enable cookies, set mode="InProc" and cookieless="UseCookies". With these configuration changes you won't have to change anything else in your code, because the session will be ensured to work using cookies (provided that cookies are enabled on the client's browser).

You seem to be unaware that the ASP.NET Session State object actually uses cookies by default to persist data across multiple requests, (although this behavior can be changed in your web.config).

Documentation

  • the web.config sessionState element
  • ASP.NET Session State
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜