ASP.NET 5 (Core): How to store objects in session-cache (ISession)?

你离开我真会死。 提交于 2020-01-01 08:05:30

问题


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).

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

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


回答1:


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

The extension methods on ISession are defined in the Microsoft.AspNet(Core).Http namespace.



来源:https://stackoverflow.com/questions/35993415/asp-net-5-core-how-to-store-objects-in-session-cache-isession

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!