With Web Forms, I could create a wrapper for a strongly typed Session:
public class MySession
{
public static MySession Current
{
get
{
MySession session = (MySession)HttpContext.Current.Session["__MySession__"];
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["__MySession__"] = session;
}
return session;
}
}
public string TestString { get; set; }
}
I am trying to do the same thing for TempData in Core:
public class MySession
{
public static MySession Current
{
get
{
var _sessionId = "_MyTempData_";
var httpContext = new HttpContextAccessor().HttpContext;
var tempDataFactory = httpContext.RequestServices.GetRequiredService<ITempDataDictionaryFactory>();
var tempData = tempDataFactory.GetTempData(httpContext);
var val = tempData.Peek(_sessionId) as string;
MySession mySession;
if (string.IsNullOrWhiteSpace(val))
{
mySession = new();
tempData[_sessionId] = JsonConvert.SerializeObject(mySession);
tempData.Save();
}
else
mySession = JsonConvert.DeserializeObject<MySession>(val);
return mySession;
}
}
public string TestString { get; set; }
}
But my TestString value is alway null:
MySession.Current.TestString = "Test";
var x = MySession.Current.TestString //always null
Is it because I was able to store the actual MySession object, so it was referenced, or something?