Session:无法在ASP.NET Core 3.0 C#中将int转换为字节[]

问题描述 投票:0回答:1

我尝试查找如何使用核心3.0中使用会话的新方法。

类似:HttpContext.Session.Set("UserID", ???);,除了我不能填写整数。

我试图在Microsoft的官方网站上查找它,但其中只有HttpContext.Session.SetInt32HttpContext.Session.SetString

您如何使用核心3.0中的新版本?

c# session httpcontext asp.net-core-3.0
1个回答
0
投票

Microsoft.AspNetCore.Http仅提供HttpContext.Session.SetInt32HttpContext.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);
    }
}

您可以在上述扩展方法中使用SerializationSystem.Text.Json e.t.c等BinaryFormatter技术选择。在here中检查这些扩展方法。

现在可以使用

byte[] bytes = ....
HttpContext.Session.Set<byte[]>(SessionKey, bytes);

byte[] newBytes = HttpContext.Session.Get<byte[]>(SessionKey);
© www.soinside.com 2019 - 2024. All rights reserved.