1、在Startup.cs的ConfigureServices方法中增加services.AddSession();
2、在Startup.cs的Configure方法中增加app.UseSession();(在UseRouting之后和UseEndpoints之前调用 UseSession)
3、在Controller中用HttpContext.Session.GetString("key")获取session,用HttpContext.Session.SetString("key", "value")设置session(key和value都是字符串,文末链接有将对象转换为json字符串作为value,在读取后反序列化成对象的)
4、在cshtml页面中用
@using Microsoft.AspNetCore.Http;
@{
HttpContext context = this.Context;
string value = context.Session.GetString("key");
}
参考:
微软文档:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0
session使用及存储对象:https://www.cnblogs.com/xuqp/p/9204227.html