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

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

问题描述

在早期版本的 Asp.Net 中,会话可以像使用静态变量一样在任何页面中访问

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

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

解决方案

2017 年 1 月 17 日修正方法以修复错误

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

<块引用>

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

Asp.Net Core 是围绕依赖注入设计的,一般来说,设计者没有提供太多对上下文信息的静态访问.更具体地说,没有等效于 System.Web.HttpContext.Current.

在控制器中,您可以通过 this.HttpContext.Session 访问会话变量,但您特别询问了如何通过控制器调用的方法访问会话 无需将会话属性作为参数传递.

因此,要做到这一点,我们需要设置自己的静态类来提供对会话的访问,并且我们需要一些代码来在启动时初始化该类.由于一个人可能希望静态访问整个 HttpContext 对象而不仅仅是 Session 我采用了这种方法.

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

使用Microsoft.AspNetCore.Http;使用系统;使用 System.Threading;命名空间 App.Web {公共静态类 AppHttpContext {静态 IServiceProvider 服务 = null;///<总结>///提供对框架服务提供者的静态访问///</总结>公共静态 IServiceProvider 服务 {获取{返回服务;}放 {如果(服务!= null){throw new Exception("一旦设置了值就不能设置.");}服务=价值;}}///<总结>///提供对当前HttpContext的静态访问///</总结>公共静态 HttpContext 当前{得到 {IHttpContextAccessor httpContextAccessor = services.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor;返回 httpContextAccessor?.HttpContext;}}}}

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

//添加访问当前HttpContext的服务services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

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

AppHttpContext.Services = app.ApplicationServices;

现在 Controller 调用的任何方法,即使是通过 async await 模式,也可以通过 AppHttpContext.Current 访问当前的 HttpContextp>

所以,如果我们使用 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天全站免登陆