using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Session; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ConsoleApp1 { public static class Sample02 { public static void Start() { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(builder => builder .ConfigureServices(collection => collection .AddDistributedMemoryCache() //基于内存的缓存服务,让Session使用,这里可以换成redis .AddSession()) //注册Session .Configure(app => app .UseSession() //使用Session .Run(ProcessAsync))) //运行中间件 .Build() .Run(); static async Task ProcessAsync(HttpContext context) { var session = context.Session; //获得context 的Session await session.LoadAsync(); //从缓存中获得 Session的状态 string sessionStartTime; if (session.TryGetValue("SessionStartTime", out var value)) //后面读取出来 { sessionStartTime = Encoding.UTF8.GetString(value); //编码 } else { sessionStartTime = DateTime.Now.ToString(CultureInfo.InvariantCulture); session.SetString("SessionStartTime", sessionStartTime); //第一次设置一个sessionStartTime } // 使用反射获取Session Key var field = typeof(DistributedSession).GetTypeInfo().GetField("_sessionKey", BindingFlags.Instance | BindingFlags.NonPublic); var sessionKey = field?.GetValue(session); //获得DistributedSession: ISession context.Response.ContentType = "text/html"; await context.Response.WriteAsync($"<html><body><ul><li>Session ID:{session.Id}</li>"); //每次会话的ID,第一次会通过相应头发给客户端,默认20分钟失效(最后一次发的请求),每次刷新都变动 await context.Response.WriteAsync($"<li>Session Key:{sessionKey}</li>"); //会话有效期不变,刷新不变,但估计过期后会变动 await context.Response.WriteAsync($"<li>Session Start Time:{sessionStartTime}</li>"); await context.Response.WriteAsync($"<li>Current Time:{DateTime.Now}</li></ul></table></body></html>"); } } } }