Asp.Net Core中使用Session
添加Session
在你的项目上基于NuGet添加:Microsoft. AspNetCore. Session。
修改Startup.cs
在startup.cs找到方法ConfigureServices(IServiceCollection services) 注入Session(这个地方是Asp.net Core pipeline):services. AddSession();
接下来我们要告诉Asp.net Core使用内存存储Session数据,在Configure(IApplicationBuilder app, …)中添加代码:app. UseSession();
Session
在MVC Controller里使用HttpContext.Session
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16using Microsoft.AspNetCore.Http;
public class HomeController:Controller
{
public IActionResult Index()
{
HttpContext.Session.SetString("code","123456");
return View();
}
public IActionResult About()
{
ViewBag.Code=HttpContext.Session.GetString("code");
return View();
}
}如果不是在Controller里,你可以注入IHttpContextAccessor
1 | public class SomeOtherClass |
存储复杂对象
存储对象时把对象序列化成一个json字符串存储。
1 | public static class SessionExtensions |
1 | var myComplexObject = new MyClass(); |
使用SQL Server或Redis存储
1、SQL Server
添加引用 “Microsoft. Extensions. Caching. SqlServer”: “1.0.0”
注入:
1 | // Microsoft SQL Server implementation of IDistributedCache. |
2、Redis
添加引用 “Microsoft. Extensions. Caching. Redis”: “1.0.0”
注入:
1 | // Redis implementation of IDistributedCache. |