c# - 执行强类型 ASP.NET MVC session 的更好方法

标签 c# asp.net-mvc session strong-typing

我正在开发一个 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/

相关文章:

c# - 为什么我需要将模型传递给 View ?

c# - Asp.NET MVC,自定义TextWriterTraceListener不创建文件

PHP session 超时为 0,但 session 仍将过期

c# - Process.GetProcessById 启用 "debug mode"

c# - MVVM 轻型从 ViewModel 发送消息到 View

asp.net-mvc - ASP.NET MVC 从操作中注入(inject)部分 View 的简洁方法

php - 如何在不被 Joomla session 覆盖的情况下获取 session 数据(来自外部 php 脚本)?

node.js - MEAN js 如何处理身份验证?

c# - 根据结果​​集更新或插入数据库中的记录

c# - 使用 NAudio 转换为 WAV 后使用 SoundPlayer 播放 MP3