我正在开发一个 ASP.NET MVC 项目并希望使用强类型 session 对象。我已经实现了以下 Controller 派生类来公开此对象:
public class StrongController<_T> : Controller
where _T : new()
{
public _T SessionObject
{
get
{
if (Session[typeof(_T).FullName] == null)
{
_T newsession = new _T();
Session[typeof(_T).FullName] = newsession;
return newsession;
}
else
return (_T)Session[typeof(_T).FullName];
}
}
}
这样我就可以为每个controller定义一个session对象,符合controller隔离的概念。是否有更好/更“正确”的方式,也许是微软官方支持的方式?
最佳答案
这样其他对象将无法访问该对象(例如 ActionFilter)。我这样做:
public interface IUserDataStorage<T>
{
T Access { get; set; }
}
public class HttpUserDataStorage<T>: IUserDataStorage<T>
where T : class
{
public T Access
{
get { return HttpContext.Current.Session[typeof(T).FullName] as T; }
set { HttpContext.Current.Session[typeof(T).FullName] = value; }
}
}
然后,我可以将 IUserDataStorage 注入(inject)到 Controller 的构造函数中,或者在 ActionFilter 中使用 ServiceLocator.Current.GetInstance(typeof(IUserDataStorage
public class MyController: Controller
{
// automatically passed by IoC container
public MyController(IUserDataStorage<MyObject> objectData)
{
}
}
当然,对于所有 Controller 都需要这个的情况(例如 ICurrentUser),您可能希望改用属性注入(inject)。
关于c# - 执行强类型 ASP.NET MVC session 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1710875/