Nav*_*eth 8 session asp.net-core-mvc asp.net-core
在早期版本的Asp.Net会话中,可以在任何页面中访问,如静态变量使用
System.Web.HttpContext.Current.Session["key"]
Run Code Online (Sandbox Code Playgroud)
在Asp.Net Core中,如何访问通过控制器调用的不同类中的会话,而不将会话属性作为所有类的构造函数中的附加参数传递
Ron*_*n C 15
修订方法1/17/17修复bug
首先,我假设您已将ASP.NET Core应用程序配置为使用会话状态.如果没有看到@slfan的答案如何通过静态变量访问ASP.NET Core中的Session?
如何在不通过控制器调用的不同类中访问会话,而不将会话属性作为所有类的构造函数中的附加参数传递
Asp.Net Core是围绕依赖注入设计的,通常设计人员不提供对上下文信息的大量静态访问.更具体地说,没有相当于System.Web.HttpContext.Current.
在控制器中,您可以访问Session vars,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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
接下来,我们需要向DI容器添加一个可以提供当前访问权限的服务HttpContext.此服务附带Core MVC框架,但默认情况下未安装.所以我们需要用一行代码"安装"它.这行在ConfigureServicesStartup.cs文件的方法中,可以位于该方法的任何位置:
//Add service for accessing current HttpContext
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Run Code Online (Sandbox Code Playgroud)
接下来,我们需要设置静态类,以便它可以访问DI容器以获取我们刚刚安装的服务.下面的代码Configure在Startup.cs文件的方法中.该行可以位于该方法的任何位置:
AppHttpContext.Services = app.ApplicationServices;
Run Code Online (Sandbox Code Playgroud)
现在Controller,即使通过异步等待模式调用的任何方法都可以访问当前HttpContext通道AppHttpContext.Current
所以,如果我们Session在Microsoft.AspNetCore.Http命名空间中使用扩展方法,我们可以保存一个int名为"Count"的会话,可以这样做:
AppHttpContext.Current.Session.SetInt32("Count", count);
Run Code Online (Sandbox Code Playgroud)
int从会话中检索一个名为"Count"的方法可以这样做:
int count count = AppHttpContext.Current.Session.GetInt32("Count");
Run Code Online (Sandbox Code Playgroud)
请享用.