.net Core Session使用

1746 ワード

Sessiong
公式ドキュメントhttps://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/app-state
  • プログラムセットMicrosoft.AspNetCore.Session
  • を追加
  • Startup.csのConfigureServicesにセッションミドルウェア設定
  • を追加
    // session   
    services.AddSession(options =>
    {
        //    Session     
        options.IdleTimeout = TimeSpan.FromDays(90);
        options.CookieHttpOnly = true;
    });
    
  • Startup.csのConfigureにセッションサービス
  • を追加
    //     MVC    
    app.UseSession();
    
  • Sessionデータ
  • を設定する
    //                   Session  
    HttpContext.Session.SetString("Key", Value);
    //    Value      byte[]
    HttpContext.Session.Set("Key", Value);
    
  • Sessionの値
  • を取得
    //      C# 7.0    out         
    loigncontext.HttpContext.Session.TryGetValue("Key", out byte[] Value);
    //     byte[]       
    var str = System.Text.Encoding.UTF8.GetString(Value)
    // 
    

    *1.オブジェクトをbyte[]に変換
    //        json        (using Newtonsoft.Json;)
    string json = JsonConvert.SerializeObject(obj);
    //json       byte[]
    byte[] serializedResult = System.Text.Encoding.UTF8.GetBytes(json);
    

    *2.byte[]をオブジェクトに変換
    // byte[]    json     
    var strJson = System.Text.Encoding.UTF8.GetString(buff);
    //  json               using Newtonsoft.Json;
    JsonConvert.DeserializeObject(strJson)
    

    *3.byte[]をオブジェクトに変換
    /// 
    ///  byte[]     
    /// 
    ///    byte[]
    ///        
    public static T Bytes2Object(byte[] buff)
    {
        string json = System.Text.Encoding.UTF8.GetString(buff);
    //        using Newtonsoft.Json;
        return JsonConvert.DeserializeObject(json);
    }