asp.net-mvc ASP.NET MVC - 如何在控制器和视图以外的地方访问会话数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/735133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:29:02  来源:igfitidea点击:

ASP.NET MVC - How to access Session data in places other than Controller and Views

asp.net-mvcsession

提问by xraminx

We can access session data in controllers and views like this:

我们可以像这样访问控制器和视图中的会话数据:

Session["SessionKey1"]

How do you access Session values from a class other than a controller or view?

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

回答by tvanfosson

I'd use dependency injection and pass the instance of the HttpContext (or just the session) to the class that needs access to the Session. The other alternative is to reference HttpContext.Current, but that will make it harder to test since it's a static object.

我会使用依赖注入并将 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"];
            ...
        }
   }

回答by Nick Berardi

You just need to call it through the HttpContextlike so:

你只需要HttpContext像这样调用它:

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

回答by Smoothcity

Here is my version of a solution for this problem. Notice that I also use a dependency injection as well, the only major difference is that the "session" object is accessed through a Singleton

这是我针对此问题的解决方案版本。请注意,我也使用了依赖注入,唯一的主要区别是“会话”对象是通过单例访问的

private iSession _Session;

private iSession InternalSession
{
    get
    {

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

Here is the SessionDecorator class, which uses a Decorator pattern to wrap the session around an interface :

这是 SessionDecorator 类,它使用装饰器模式将会话包装在接口周围:

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

Hope this helps :)

希望这可以帮助 :)

回答by Tony Borf

I would also wrap all session variables into a single class file. That way you can use intelliSense to select them. This cuts down on the number of paces in code where you need to specify the "strings" for the session.

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

回答by Chuck

Haven't done it myself, but this sample from Chad Meyer's blog might help (from this post: http://www.chadmyers.com/Blog/archive/2007/11/30/asp.net-webforms-and-mvc-in-the-same-project.aspx)

我自己还没有做过,但是来自 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);
}