这样做的强类型ASP.NET MVC的会话更好的办法 [英] Better way of doing strongly-typed ASP.NET MVC sessions

查看:99
本文介绍了这样做的强类型ASP.NET MVC的会话更好的办法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个ASP.NET MVC项目,并希望使用强类型会话对象。我已实现了以下控制器的派生类揭露这个对象:

I am developing an ASP.NET MVC project and want to use strongly-typed session objects. I have implemented the following Controller-derived class to expose this object:

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];
        }
    }

}

这使我来定义会话对象的每个控制器,它是在与控制器隔离的概念线。有没有更好/更正确的方式,或许是目前正式支持通过Microsoft?

This allows me to define a session object for each controller, which is in line with the concept of controller isolation. Is there a better/more "correct" way, perhaps something that is officially supported by Microsoft?

推荐答案

此方式与其它对象将不能访问这个对象(例如ActionFilter)。我这样做,是这样的:

This way other objects won't have access to this object (e.g. ActionFilter). I do it like this:

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控制器的构造函数,或使用ServiceLocator.Current.GetInstance(typeof运算(IUserDataStorage&LT; T&GT;))。里面ActionFilter

Then, I can either inject IUserDataStorage into controller's constructor, or use ServiceLocator.Current.GetInstance(typeof(IUserDataStorage<T>)) inside ActionFilter.

public class MyController: Controller
{
   // automatically passed by IoC container
   public MyController(IUserDataStorage<MyObject> objectData)
   {
   }
}

课程的情况下,当全部控制器需要这个(例如ICurrentUser),你可能需要使用注射财产代替。

Of course for cases when all controllers need this (e.g. ICurrentUser) you may want to use property injection instead.

这篇关于这样做的强类型ASP.NET MVC的会话更好的办法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆