万金流
初次使用博客园,目前感觉还不错。 不知不觉用了4年零4个月了,越来越喜欢博客园。

为了减小体积,core默认包含的东西比较少。MVC模板里默认没有包含Session。

以下内容VS2022版本 17.2.4调试通过。

添加方法:

在主程序(Program.cs)里添加session的有关设置和管道中间件

 1 public class Program
 2     {
 3         public static void Main(string[] args)
 4         {
 5             var builder = WebApplication.CreateBuilder(args);
 6 
 7             // Add services to the container.
 8             builder.Services.AddControllersWithViews();
 9 
10             builder.Services.AddDistributedMemoryCache();
11 
12             builder.Services.AddSession(options =>
13             {
14                 options.IdleTimeout = TimeSpan.FromMinutes(20);
15                 options.Cookie.Name = "test";
16             });
17 
18             var app = builder.Build();
19 
20             // Configure the HTTP request pipeline.
21             if (!app.Environment.IsDevelopment())
22             {
23                 app.UseExceptionHandler("/Home/Error");
24             }
25             app.UseStaticFiles();
26 
27             app.UseRouting();
28 
29             app.UseAuthorization();
30 
31             app.UseSession();
32 
33             app.MapControllerRoute(
34                 name: "default",
35                 pattern: "{controller=Home}/{action=Index}/{id?}");
36 
37             app.Run();
38         }
39     }

说明:

1、10-16行为设置并添加Session服务。第10行在使用分布式缓存的时候开启,此处也可以不添加;第14行设置默认超时时间;第15行给Session起个名字,能防止同一主机多个网站Session混乱。

如果想全部使用默认值,可以直接简写为”builder.Services.AddSession();“

2、第31行使用Session中间件。位置一定要在UseRouting之后,Map之前。

至此,可以使用Session。 需要注意:

1、MVC中的Session在“ControllerBase.HttpContext"中,故只能在控制器中使用。访问方式为”HttpContext.Session“

2、对Session的读写,需要用规定的扩展方法:


 

举例:

一个简单的累加器,用户每访问页面一次,数字加一。

控制器:

 1 public class HomeController : Controller
 2     {
 3         public IActionResult Index()
 4         {
 5             var t=HttpContext.Session.GetInt32("sum")??-1;
 6             t++;
 7             HttpContext.Session.SetInt32("sum", t);
 8             ViewData["sum"] = t; 
 9             return View();
10         }
11     }

页面:

求和值为:@(ViewData["sum"]??"没有值")

运行效果:

 

不同Session,值互不干扰。

另:在页面上使用Session,可以用Context取代控制器里的HttpContext。两者指向同一对象。

 参考:

1、微软官方文档”https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-6.0“

2、微软官方文档”https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/http-context?view=aspnetcore-6.0“

 鸣谢:”.Virus.“,QQ:7327594;”FriskTale“,QQ:944208851

posted on 2022-06-16 15:38  万金流  阅读(944)  评论(0编辑  收藏  举报