如何通过静态变量访问ASP.NET Core中的Session? [英] How to access the Session in ASP.NET Core via static variable?

查看:480
本文介绍了如何通过静态变量访问ASP.NET Core中的Session?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在早期版本的Asp.Net会话中,可以使用

在任何页面(如静态变量)中进行访问

System.Web.HttpContext.Current.Session["key"]

在Asp.Net Core中,如何访问通过控制器调用的不同类中的会话,而不在所有类的构造函数中将session属性作为附加参数传递

解决方案

修订的方法1/17/17修复错误

首先,我假设您已将ASP.NET Core应用程序配置为使用会话状态.如果看不到@slfan的答案如何通过静态访问ASP.NET Core中的会话变量?

如何通过控制器调用不同类中的会话,而不在所有类的构造函数中将session属性作为附加参数传递

Asp.Net Core是围绕依赖项注入设计的,通常,设计人员没有提供太多静态访问上下文信息的方法.更具体地说,没有等效于System.Web.HttpContext.Current.

在Controllers中,您可以通过this.HttpContext.Session访问Session var,但是您具体询问了如何从控制器不通过传递session属性作为参数的方法中访问会话./p>

因此,要执行此操作,我们需要设置自己的静态类以提供对会话的访问,并且需要一些代码以在启动时初始化该类.因为一个人可能希望静态访问整个HttpContext对象,而不仅仅是我采用的Session对象.

所以首先我们需要静态类:

using Microsoft.AspNetCore.Http; 
using System;
using System.Threading;

namespace App.Web {

    public static class AppHttpContext {
        static IServiceProvider services = null;

        /// <summary>
        /// Provides static access to the framework's services provider
        /// </summary>
        public static IServiceProvider Services {
            get { return services; }
            set {
                if(services != null) {
                    throw new Exception("Can't set once a value has already been set.");
                }
                services = value;
            }
        }

        /// <summary>
        /// Provides static access to the current HttpContext
        /// </summary>
        public static HttpContext Current {
            get {
                IHttpContextAccessor httpContextAccessor = services.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor;
                return httpContextAccessor?.HttpContext;
            }
        } 

    }
}

接下来,我们需要向DI容器添加一个服务,该服务可以提供对当前HttpContext的访问.此服务随Core MVC框架一起提供,但默认情况下未安装.因此,我们需要用单行代码安装"它.该行位于Startup.cs文件的ConfigureServices方法中,并且可以位于该方法的任何位置:

//Add service for accessing current HttpContext
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();    

接下来,我们需要设置我们的静态类,以便它可以访问DI容器以获得我们刚刚安装的服务.下面的代码在Startup.cs文件的Configure方法中.该行可以位于该方法中的任何位置:

AppHttpContext.Services = app.ApplicationServices; 

现在,Controller调用的任何方法,甚至通过异步等待模式,都可以通过AppHttpContext.Current

访问当前的HttpContext.

因此,如果我们在Microsoft.AspNetCore.Http命名空间中使用Session扩展方法,则可以将名为"Count"的int保存到会话中,如下所示:

AppHttpContext.Current.Session.SetInt32("Count", count);

从会话中检索名为"Count"的int可以这样完成:

int count count = AppHttpContext.Current.Session.GetInt32("Count");

享受.

In earlier version of Asp.Net session can be accessed in any page like a static variable using

System.Web.HttpContext.Current.Session["key"]

In Asp.Net Core, How to access session in different class called via controller, without passing the session property as an additional parameter in the constructor of all classes

解决方案

Revised approach 1/17/17 to fix bug

First, I'll assume that you have your ASP.NET Core application configured to use session state. If not see @slfan's answer How to access the Session in ASP.NET Core via static variable?

How to access session in different class called via controller, without passing the session property as an additional parameter in the constructor of all classes

Asp.Net Core is designed around dependency injection and in general the designers didn't provide much static access to context information. More specifically there is no equivalent to System.Web.HttpContext.Current.

In Controllers you can get access to Session vars via this.HttpContext.Session but you specifically asked how to get access to the session from methods called by the controller without passing the session property as a parameter.

So, to do this we need to setup our own static class to provide access to session and we need some code to initialize that class at startup. Since it's likely that a person may want static access to the whole HttpContext object and not just the Session I took that approach.

So first we need the static class:

using Microsoft.AspNetCore.Http; 
using System;
using System.Threading;

namespace App.Web {

    public static class AppHttpContext {
        static IServiceProvider services = null;

        /// <summary>
        /// Provides static access to the framework's services provider
        /// </summary>
        public static IServiceProvider Services {
            get { return services; }
            set {
                if(services != null) {
                    throw new Exception("Can't set once a value has already been set.");
                }
                services = value;
            }
        }

        /// <summary>
        /// Provides static access to the current HttpContext
        /// </summary>
        public static HttpContext Current {
            get {
                IHttpContextAccessor httpContextAccessor = services.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor;
                return httpContextAccessor?.HttpContext;
            }
        } 

    }
}

Next we need to add a service to the DI container that can provide access to the current HttpContext. This service ships with the Core MVC framework but is not installed by default. So we need to "install" it with a single line of code. This line goes in the ConfigureServices method of the Startup.cs file and can be located anywhere in that method:

//Add service for accessing current HttpContext
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();    

Next we need to setup our static class so that it has access to the DI container to obtain the service we just installed. The code below goes in the Configure method of the Startup.cs file. This line can be be located anywhere in that method:

AppHttpContext.Services = app.ApplicationServices; 

Now any method called by the Controller, even via the async await pattern, can access the current HttpContext via AppHttpContext.Current

So, if we use the Session extension methods in the Microsoft.AspNetCore.Http namespace, we can save an int called "Count" to session could be done like this:

AppHttpContext.Current.Session.SetInt32("Count", count);

And retrieving an int called "Count" from session could be done like this:

int count count = AppHttpContext.Current.Session.GetInt32("Count");

Enjoy.

这篇关于如何通过静态变量访问ASP.NET Core中的Session?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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