【发布时间】:2022-01-18 05:00:31
【问题描述】:
使用 Web 表单,我可以为强类型会话创建包装器:
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; }
}
我正在尝试对 Core 中的 TempData 做同样的事情:
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; }
}
但我的 TestString 值始终为空:
MySession.Current.TestString = "Test";
var x = MySession.Current.TestString //always null
是因为我能够存储实际的 MySession 对象,所以它被引用了,还是什么?
【问题讨论】:
-
我会说你最好让你的
MySession成为一个实例类,让ctor接受IHttpContextAccessor并将MySession注册为一个作用域服务。 -
new HttpContextAccessor()你不应该这样做。HttpContextAccessor()的新实例不会为您提供控制器使用的相同 httpContext。此外,每次调用此 Current 属性都会创建一个新的 HttpContextAccessor ,这将导致一切都是新的。甚至临时数据字典。这就是为什么即使在您先设置后也无法取回该值
标签: c# asp.net-mvc asp.net-core .net-core