> 文章列表 > 如何通过静态变量访问 ASP.NET Core 中的 Session?

如何通过静态变量访问 ASP.NET Core 中的 Session?

如何通过静态变量访问 ASP.NET Core 中的 Session?

本文介绍了如何通过静态变量访问 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

转载:https://www.it1352.com/2810722.html