Analyzing the method of using Session in Asp. net Core
- 2021-09-11 19:52:41
- OfStack
Preface
2017 has started so quietly, and 2017 is another particularly important year for me.
On New Year's Day holiday, I wrote an Asp. net Core verification code to log in at home. In the process of doing demo, I encountered two small problems. The first one was to reference dll in Asp. net Core. In the past, we quoted DLL directly, but this is not possible in Core. It must be added based on NuGet or project. json, and then saving VS will start restoring the class library.
The second is the problem of using Session. Using Session in Core requires adding Session class library.
Add Session
Add to your project based on NuGet: Microsoft. AspNetCore. Session.
Modify startup. cs
Find the method in startup. cs ConfigureServices (IServiceCollection services) Inject Session (this place is Asp. net Core pipeline): services. AddSession ();
Next, we tell Asp. net Core to use memory to store Session data, and add code to Configure (IApplicationBuilder app,...): app. UserSession ();
Session
1. Use HttpContext. Session in MVC Controller
using 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();
}
}
2. If it is not in Controller, you can inject IHttpContextAccessor
public class SomeOtherClass
{
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session=> _httpContextAccessor.HttpContext.Session;
public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor=httpContextAccessor;
}
public void Set()
{
_session.SetString("code","123456");
}
public void Get()
{
string code = _session.GetString("code");
}
}
Store complex objects
When storing an object, serialize the object into an json string for storage.
public static class SessionExtensions
{
public static void SetObjectAsJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetObjectFromJson<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}
var myComplexObject = new MyClass();
HttpContext.Session.SetObjectAsJson("Test", myComplexObject);
var myComplexObject = HttpContext.Session.GetObjectFromJson<MyClass>("Test");
Use SQL Server or Redis storage
1. SQL Server
Add reference "Microsoft. Extensions. Caching. SqlServer": "1.0. 0"
Inject:
// Microsoft SQL Server implementation of IDistributedCache.
// Note that this would require setting up the session state database.
services.AddSqlServerCache(o =>
{
o.ConnectionString = "Server=.;Database=ASPNET5SessionState;Trusted_Connection=True;";
o.SchemaName = "dbo";
o.TableName = "Sessions";
});
2. Redis
Add reference "Microsoft. Extensions. Caching. Redis": "1.0. 0"
Inject:
// Redis implementation of IDistributedCache.
// This will override any previously registered IDistributedCache service.
services.AddSingleton<IDistributedCache, RedisCache>();