在start.cs文件的ConfigureServices(...)中配置。
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache(); //必须使用,代表在内存中存放session。当然也可以使用sqlserver或redis来存放,使用对应的方法
// services.AddSession(); //在此方法中采用默认配置
//以下配置使用Cookie,同时设置过期时间为30分钟
services.AddSession(opt =>
{
opt.IdleTimeout = new TimeSpan(0, 30, 0);
opt.Cookie = new Microsoft.AspNetCore.Http.CookieBuilder
{
Name = "myCookie",
IsEssential = true
};
});
}
在configure(...)方法中使用app.UseSession()来使用Session中间件。
具体使用可以使用SetString,SetInt32,Set三个方法,前两个是扩展方法。如:
HttpContext.Session.SetString("JWToken", "xxxxxxx");