Open snowchenlei opened 4 years ago
FYI there are several examples of doing this with extension methods. We didn't bake it in because generic serialization is extremely complicated (see how much work it is in MVC).
See these ISession extensions that cover the same scenario: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1#set-and-get-session-values
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);
}
}
OK, I know, thank you! Can Support The JsonSerialization Interface?Like IDistributedCache. Because Now System.Text.Json Is Provided at .Net Core 3!
Fair point, yes it should be easy to modify the example like that. I'll convert this to a documentation bug and see about getting a System.Text.Json sample added for both Session and IDistributedCache.
Here's the other doc that could use a copy of the updated code sample: https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-3.1
System.Text.Json samples: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to SerializeToUtf8Bytes looks like the best option here, it skips the extra string allocation. (untested)
public static void Set<T>(this ISession session, string key, T value)
{
session.Set(key, JsonSerializer.SerializeToUtf8Bytes<T>(value, new JsonSerializerOptions()));
}
public static Task SetAsync<T>(this IDistributedCache cache, string key, T value)
{
return cache.SetAsync(key, JsonSerializer.SerializeToUtf8Bytes<T>(value, new JsonSerializerOptions()));
}
These examples but be on this page. Please add them.
Moved to Distributed caching master page #17553
Seems like this should support some Stream
/pipeline/iasyncenumerable stream options rather than having to load the entire thing into memory before being able to do anything.
Is your feature request related to a problem? Please describe.
I Need Get/Set A Type Not byte[]
Describe the solution you'd like
@Rick-Anderson edit: Integrated issue
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.