Caching Serialized Objects
Store and retrieve complex objects.
Caching More Than Strings
Real apps cache objects, not just strings. Since IDistributedCache stores bytes, you must serialize your object to a byte/string representation, and deserialize on the way out. JSON is the usual choice.
Serializing With System.Text.Json
Use System.Text.Json to turn an object into a JSON string, then store it with SetStringAsync.
using System.Text.Json;
var product = new Product { Id = 1, Name = "Coffee", Price = 4.5m };
string json = JsonSerializer.Serialize(product);
await _cache.SetStringAsync("product:1", json);All lessons in this course
- IDistributedCache Abstraction
- Connecting to Redis
- Cache Patterns and Expiration
- Caching Serialized Objects