码迷,mamicode.com
首页 > Web开发 > 详细

.net 5.0 - Session的使用

时间:2021-04-19 15:18:17      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:sso   def   安装   get   pad   使用   20px   edm   设置   

NuGet安装
Microsoft.AspNetCore.Session
Microsoft.AspNetCore.Http.Extensions
Startup.cs中注册
// 添加一个内存缓存
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
    // 设置10秒钟Session过期来测试
    options.IdleTimeout = TimeSpan.FromSeconds(10);
    options.Cookie.HttpOnly = true;
});

 

app.UseSession();
Controller中使用Session
HttpContext.Session.SetString("param", str);
string value = HttpContext.Session.GetString("param");
非Controller中使用Session
public class SessionTestClass
{
    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");
    }
}
 ISession的扩展,存储复杂对象
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 myTestObject = new MyTestClass();
HttpContext.Session.SetObjectAsJson("SessionTest", myTestObject);
var myComplexObject = HttpContext.Session.GetObjectFromJson<MyClass>("SessionTest");

.net 5.0 - Session的使用

标签:sso   def   安装   get   pad   使用   20px   edm   设置   

原文地址:https://www.cnblogs.com/gygtech/p/14669253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!