2017 年 1 月 17 日修订的方法以修复错误
首先,我假设您已将 ASP.NET Core 应用程序配置为使用会话状态。如果没有看到@slfan 的回答How to access the Session in ASP.NET Core via static variable?
如何在通过控制器调用的不同类中访问会话,而不将会话属性作为附加参数传递给所有类的构造函数
Asp.Net Core 是围绕依赖注入设计的,通常设计者没有提供对上下文信息的太多静态访问。更具体地说,没有等同于System.Web.HttpContext.Current。
在控制器中,您可以通过this.HttpContext.Session 访问会话变量,但您特别询问了如何通过控制器调用的方法访问会话而不将会话属性作为参数传递。
因此,要做到这一点,我们需要设置自己的静态类来提供对会话的访问,并且我们需要一些代码来在启动时初始化该类。由于一个人可能希望静态访问整个 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");
享受。