ASP.NET 5(核心):如何存储在会话缓存(ISession的)对象? [英] ASP.NET 5 (Core): How to store objects in session-cache (ISession)?

查看:1185
本文介绍了ASP.NET 5(核心):如何存储在会话缓存(ISession的)对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个ASP.NET MVC 5 6(核心)应用程序。现在我来到了一个点,我需要存储(set和get)在会话高速缓存中的对象(的Isession )。

I am writing an ASP.NET 5 MVC 6 (Core) application. Now I came to a point where I need to store (set and get) an object in the session-cache (ISession).

正如你可能知道,在设置 的Isession 的-method需要字节数组获取 -method返回之一。

As you may know, the Set-method of ISession takes a byte-array and the Get-method returns one.

在非核心应用我会使用的BinaryFormatter 我的对象转换。但是,我怎么能做到这一点的一个核心应用?

In a non-core-application I would use the BinaryFormatter to convert my object. But how can I do it in a core-application?

推荐答案

我会去与序列化对象以JSON和使用在的Isession 将其保存为字符串

I'd go with serializing the objects to JSON and use the extensions methods on ISession to save them as string's.

// 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);

ISession的扩展方法中定义在 Microsoft.AspNet(核心).Http 命名空间。

这篇关于ASP.NET 5(核心):如何存储在会话缓存(ISession的)对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆