【问题标题】:capitalize when get a response from redis cache从 redis 缓存中获取响应时大写
【发布时间】:2022-01-15 14:45:28
【问题描述】:

我有一个问题,我缓存了来自我的 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));
            }
        }

【问题讨论】:

标签: .net asp.net-core stackexchange.redis capitalization


【解决方案1】:

这个问题与 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);

结果:

【讨论】:

    猜你喜欢
    • 2013-03-14
    • 2020-05-16
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 2018-04-03
    相关资源
    最近更新 更多