English 中文(简体)
ASP.NET MVC-如何在控制器和视图之外的位置访问会话数据
原标题:
  • 时间:2009-04-09 17:21:27
  •  标签:

我们可以访问控制器和视图中的会话数据,如下所示:

Session["SessionKey1"]

如何从控制器或视图以外的类访问会话值?

最佳回答

我将使用依赖注入,并将HttpContext的实例(或仅会话)传递给需要访问会话的类。另一种选择是引用HttpContext.Current,但这将使测试变得更加困难,因为它是一个静态对象。

   public ActionResult MyAction()
   {

       var foo = new Foo( this.HttpContext );
       ...
   }


   public class Foo
   {
        private HttpContextBase Context { get; set; }

        public Foo( HttpContextBase context )
        {
            this.Context = context;
        }

        public void Bar()
        {
            var value = this.Context.Session["barKey"];
            ...
        }
   }
问题回答

您只需要通过HttpContext调用它,如下所示:

HttpContext.Current.Session["MyValue"] = "Something";

这是我对这个问题的解决方案。请注意,我还使用了依赖项注入,唯一的主要区别是通过Singleton访问“会话”对象

private iSession _Session;

private iSession InternalSession
{
    get
    {

        if (_Session == null)
        {                
           _Session = new SessionDecorator(this.Session);
        }
        return _Session;
    }
}

以下是SessionDecorator类,它使用Decorator模式将会话封装在接口周围:

public class SessionDecorator : iSession
{
    private HttpSessionStateBase _Session;
    private const string SESSIONKEY1= "SESSIONKEY1";
    private const string SESSIONKEY2= "SESSIONKEY2";

    public SessionDecorator(HttpSessionStateBase session)
    {
        _Session = session;
    }

    int iSession.AValue
    {
           get
        {
            return _Session[SESSIONKEY1] == null ? 1 : Convert.ToInt32(_Session[SESSIONKEY1]);
        }
        set
        {
            _Session[SESSIONKEY1] = value;
        }
    }

    int iSession.AnotherValue
    {
        get
        {
            return _Session[SESSIONKEY2] == null ? 0 : Convert.ToInt32(_Session[SESSIONKEY2]);
        }
        set
        {
            _Session[SESSIONKEY2] = value;
        }
    }
}`

希望这能有所帮助:)

我自己还没有做过,但Chad Meyer博客中的这个样本可能会有所帮助(来自本文:http://www.chadmyers.com/Blog/archive/2007/11/30/asp.net-webforms-and-mvc-in-the-same-project.aspx

[ControllerAction]
public void Edit(int id)
{
    IHttpSessionState session = HttpContext.Session;

    if (session["LoggedIn"] == null || ((bool)session["LoggedIn"] != true))
        RenderView("NotLoggedIn");

    Product p = SomeFancyDataAccess.GetProductByID(id);

    RenderView("Edit", p);
}

我还将所有会话变量打包到一个类文件中。这样,您就可以使用intelliSense来选择它们。这减少了代码中需要为会话指定“字符串”的步数。





相关问题
热门标签