.net Core Session使用
1746 ワード
Sessiong
公式ドキュメントhttps://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/app-stateプログラムセットMicrosoft.AspNetCore.Session を追加 Startup.csのConfigureServicesにセッションミドルウェア設定 を追加 Startup.csのConfigureにセッションサービス を追加 Sessionデータ を設定する Sessionの値 を取得
*1.オブジェクトをbyte[]に変換
*2.byte[]をオブジェクトに変換
*3.byte[]をオブジェクトに変換
公式ドキュメントhttps://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/app-state
// session
services.AddSession(options =>
{
// Session
options.IdleTimeout = TimeSpan.FromDays(90);
options.CookieHttpOnly = true;
});
// MVC
app.UseSession();
// Session
HttpContext.Session.SetString("Key", Value);
// Value byte[]
HttpContext.Session.Set("Key", Value);
// 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);
}