我尝试查找如何使用核心3.0中使用会话的新方法。
类似:HttpContext.Session.Set("UserID", ???);
,除了我不能填写整数。
我试图在Microsoft的官方网站上查找它,但其中只有HttpContext.Session.SetInt32
或HttpContext.Session.SetString
。
您如何使用核心3.0中的新版本?
Microsoft.AspNetCore.Http
仅提供HttpContext.Session.SetInt32
或HttpContext.Session.SetString
。检查文档在here。
您可以使用以下扩展方法来设置和获取任何原始和引用类型对象:
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) :
JsonConvert.DeserializeObject<T>(value);
}
}
您可以在上述扩展方法中使用Serialization
或System.Text.Json
e.t.c等BinaryFormatter
技术选择。在here中检查这些扩展方法。
现在可以使用
byte[] bytes = ....
HttpContext.Session.Set<byte[]>(SessionKey, bytes);
byte[] newBytes = HttpContext.Session.Get<byte[]>(SessionKey);