ASP.NET 5(核心):如何在会话缓存(ISession)中存储对象?

eva*_*que 13 c# bytearray session-state type-conversion asp.net-core

我正在编写ASP.NET 5 MVC 6(核心)应用程序.现在我来到了一个需要在session-cache(ISession)中存储(设置和获取)对象的点.

你可能知道,Set-method ISession取a byte-arrayGet-method返回一个.

在非核心应用程序中,我会使用它BinaryFormatter来转换我的对象.但是我怎么能在核心应用程序中做到这一点?

Hen*_*ema 27

我将对象序列化为JSON并使用扩展方法ISession将它们保存为string.

// Save
var key = "my-key";
var str = JsonConvert.SerializeObject(obj);
context.Session.SetString(key, str);

// Retrieve
var str = context.Session.GetString(key);
var obj = JsonConvert.DeserializeObject<MyType>(str);
Run Code Online (Sandbox Code Playgroud)

扩展方法on ISessionMicrosoft.AspNet(Core).Http命名空间中定义.

  • 您可以在dotnet github repo上阅读[关于二进制序列化的讨论](https://github.com/dotnet/corefx/issues/6564),以及为什么不支持它. (2认同)