0

I have a problem that I cache a response from my API. First, my entity does not capitalize but when cached from Redis server it auto-capitalizes my entity. How do I fix that,

Here is picture

First-time response

The next now with cached from Redis server

Here is my code for cache response

 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));
            }
        }
Dat
  • 85
  • 12
  • it is not redis, it is json serilizer: look at this https://stackoverflow.com/questions/34070459/newtonsoft-jsonserializer-lower-case-properties-and-dictionary – mohammadreza Dec 11 '21 at 11:07

1 Answers1

2

The issue relates to the Asp.net core API (I suppose the Asp.net core version is 3.0+ and it will use the System.Text.Json to serialize and deserialize JSON), by default, it will use the camel case for all JSON property names, like this:

enter image description here

To disable the camel case, you could set the JsonSerializerOptions.PropertyNamingPolicy property to null. Update the following code in the ConfigureServices method:

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

Then when we call the API method, the result is like this: In this sample, I'm creating an Asp.net 5 application.

enter image description here

The reason the cached response works well is that you are using the Newtonsoft.Json to serialize and deserialize JSON. You can refer to the following code:

        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);

The result:

enter image description here

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30