Reputation: 13955
I'm trying to store session data in a cookie. The idea is to store the object, which is pretty small, as a json string in a cookie. I'm using a modified version of a class example found in an answer in this thread:
Is this technique of ASP.NET session access multi-user-safe?
Here's what I'm trying...
using System;
using Newtonsoft.Json;
using System.Web;
namespace SomeNameSpace
{
public class MySession
{
// private constructor
private MySession()
{
SomeString = string.Empty;
MyDate = DateTime.Now;
UserId = 0;
}
// Gets the current session.
public static MySession Current
{
get
{
MySession session = null;
if (HttpContext.Current.Request.Cookies["Session"].Value != null)
{
// This is where I'm having trouble. Neither of these work:
session = JsonConvert.DeserializeObject<MySession>(HttpContext.Current.Request.Cookies["Session"].Value);
session = (MySession)JsonConvert.DeserializeObject(HttpContext.Current.Request.Cookies["Session"].Value);
}
if (session == null)
{
session = new MySession();
HttpContext.Current.Response.Cookies["Session"].Value = JsonConvert.SerializeObject(session);
}
return session;
}
}
public string SomeString { get; set; }
public DateTime MyDate { get; set; }
public int UserId { get; set; }
}
}
This line:
session = JsonConvert.DeserializeObject<MySession>(HttpContext.Current.Response.Cookies["Session"].Value);
Does not throw an error. But the problem is, it kicks off the constructor, and so it always returns the object with the default values.
This line:
session = (MySession)JsonConvert.DeserializeObject(HttpContext.Current.Response.Cookies["Session"].Value);
Throws an error:
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'SomeNameSpace.MySession'
How do I get this done?
Thanks!!
Upvotes: 1
Views: 3557
Reputation: 151674
You're reading the response cookie of key "Session", which is never set at that point. You need to read the request cookie.
That being said, if this is session data, you don't want to store it in user-readable and user-editable cookies.
Upvotes: 1