You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过System.Text.JSON将.NET会话数据以JSON格式存储到Redis?

解决方案

要让Session数据以JSON格式存储到Redis,核心是替换StackExchangeRedisCache默认的二进制序列化器,改用基于System.Text.Json的自定义序列化器。具体步骤如下:

1. 实现自定义JSON序列化器

创建一个实现IDistributedCacheSerializer接口的类,用System.Text.Json处理序列化和反序列化逻辑:

using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;

public class JsonCacheSerializer : IDistributedCacheSerializer
{
    private readonly JsonSerializerOptions _jsonOptions;

    // 允许传入自定义JSON配置,默认使用驼峰命名
    public JsonCacheSerializer(JsonSerializerOptions? options = null)
    {
        _jsonOptions = options ?? new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            WriteIndented = false
        };
    }

    // 序列化对象为UTF-8字节数组
    public byte[] Serialize<T>(T value)
    {
        return JsonSerializer.SerializeToUtf8Bytes(value, _jsonOptions);
    }

    // 从字节数组反序列化为指定类型
    public T? Deserialize<T>(byte[] bytes)
    {
        return JsonSerializer.Deserialize<T>(bytes, _jsonOptions);
    }
}

2. 配置Redis缓存使用自定义序列化器

修改Program.cs中的Redis缓存配置,指定使用上面的JSON序列化器:

// Program.cs 
...
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("Redis");
    // 替换默认序列化器为自定义JSON序列化器
    options.Serializer = new JsonCacheSerializer();
    // 如果需要自定义JSON行为,比如处理循环引用,可以传入配置:
    // options.Serializer = new JsonCacheSerializer(new JsonSerializerOptions
    // {
    //     ReferenceHandler = ReferenceHandler.IgnoreCycles,
    //     WriteIndented = true
    // });
});

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromDays(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
    options.Cookie.MaxAge = TimeSpan.FromDays(365);
});
...

说明

Session中间件依赖IDistributedCache实现,所以只要替换了StackExchangeRedisCache的序列化器,Session数据就会自动以JSON格式(UTF-8字节数组)存储到Redis,不再使用默认的二进制格式。

内容的提问来源于stack exchange,提问作者IvanD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:12:37