Session and TempData variables can be used in MVC controllers to pass variables between actions or from actions to views, however if you want to pass complex objects through using these variables the base classes need to be extended to serialize/deserialize the provided objects to/from JSON.

public static class SessionExtensions
{
	public static void SetObjectAsJson(this ISession session, string key, object value)
	{
		session.SetString(key, JsonConvert.SerializeObject(value));
	}

	public static T GetObjectFromJson<T>(this ISession session, string key)
	{
		var value = session.GetString(key);
		return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
	}
}
public static class TempDataExtensions
{
	public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
	{
		tempData[key] = JsonConvert.SerializeObject(value);
	}

	public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
	{
		object o;
		tempData.TryGetValue(key, out o);
		return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
	}
}

Once the above classes have been created the desired object can be stored like so.

HttpContext.Session.SetObjectAsJson("user", user);
TempData.Put<User>("user", user);

And retrieved with the following.

User userTemp = TempData.Get<User>("user");
User userSession = HttpContext.Session.GetObjectFromJson<User>("user");

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *