问题
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