从 redis 缓存中获取响应时大写

capitalize when get a response from redis cache

我在缓存来自 API 的响应时遇到问题。首先,我的实体没有大写,但是当从 Redis 服务器缓存时,它会自动大写我的实体。我该如何解决,

这是图片

First-time response

The next now with cached from Redis server

这是我的缓存响应代码

 public async Task CacheResponseAsync(string key, object response, TimeSpan timeToLive)
        {
            if (response == null)
            {
                return;
            }

            var serializedResponse = JsonConvert.SerializeObject(response);

            await _distributedCache.SetStringAsync(key, serializedResponse, new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = timeToLive
            });
        }
 public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var cacheSetting = context.HttpContext.RequestServices.GetRequiredService<RedisCacheSetting>();

            if (!cacheSetting.Enabled)
            {
                await next();
                return;
            }
            var cacheService = context.HttpContext.RequestServices.GetRequiredService<IResponseCacheService>();
            var cacheKey = GenerateKeyFromRequest(context.HttpContext.Request);

            var cacheResponse = await cacheService.GetCacheResponseAsync(cacheKey);

            if (!string.IsNullOrEmpty(cacheResponse))
            {
                var rs = new ContentResult
                {
                    Content = cacheResponse,
                    ContentType = "application/json",
                    StatusCode = 200,
                };

                context.Result = rs;

                return;
            }

            var executedContext = await next();

            if (executedContext.Result is ObjectResult okObjectResult)
            {
                await cacheService.CacheResponseAsync(cacheKey, okObjectResult.Value, TimeSpan.FromSeconds(_timeToLiveSeconds));
            }
        }

问题涉及Asp.net核心API(我假设Asp.net核心版本是3.0+,它将使用System.Text.Json序列化和反序列化JSON), 默认情况下,它会为所有 JSON 属性 名称使用驼峰式大小写,如下所示:

要禁用驼峰式大小写,您可以将 JsonSerializerOptions.PropertyNamingPolicy 属性 设置为 null。在 ConfigureServices 方法中更新以下代码:

        services.AddControllers().AddJsonOptions(options => {
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        }); 

然后当我们调用 API 方法时,结果是这样的: 在这个示例中,我正在创建一个 Asp.net 5 应用程序。

缓存响应运行良好的原因是您使用 Newtonsoft.Json 序列化和反序列化 JSON。您可以参考以下代码:

        List<UserModel> users = new List<UserModel>()
        {
            new UserModel(){ Username="David", EmailAddress="david@hotmail.com"},
            new UserModel(){ Username="John", EmailAddress="john@hotmail.com"},
        };
        //using System.Text.Json and camelcase.
        var serializeOptions = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            WriteIndented = true
        };
        var jsonresult = JsonSerializer.Serialize(users, serializeOptions);
        //using System.Text.Json without camelcase.
        var serializeOptions2 = new JsonSerializerOptions
        {
            PropertyNamingPolicy = null,
            WriteIndented = true
        };
        var jsonresult2 = JsonSerializer.Serialize(users, serializeOptions2);
        //using Newtonsoft.json
        var serializedResponse = Newtonsoft.Json.JsonConvert.SerializeObject(users);

结果: