1.首先我们要创建一个静态类

  public static class MyHttpContext
{
public static IServiceProvider ServiceProvider;
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
return context;
}
} }

2: 然后在startup.cs文件中

  在Configure方法 添加

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

3. 改写ConfigureServices方法

public void Configure(IApplicationBuilder app, IHostingEnvironment env,  IServiceProvider svp)
{
///省n多代码 Models.MyHttpContext.ServiceProvider = svp }

在Configure方法的参数中加IServiceProvider svp;并在方法体中加 Models.MyHttpContext.ServiceProvider = svp; 其中MyHttpContext和声明的静态类名是一样的;

在程序中使用存储session就可以用 Models.MyHttpContext.Current.Session.Set("key", "value");

当然也可以把类名MyHttpContext改成HttpContext这样在程序中就是Models.HttpContext.Current.Session.Set("key", “value”)和之前的asp.net使用时一样的;

转自:https://www.cnblogs.com/DSC1991/p/9240327.html

https://www.cnblogs.com/zhangkjun/p/6143388.html

05-03 22:32