Cache a success response and load once it faied

21 views Asked by At

I am calling some endpoints(they are GRPC). I want to Cache the response if it was a success and load the success response in case of failure. I used a Custom HTTP client to handle this scenario.

This my ChacheHandler:

public class CacheHandler : DelegatingHandler
{
    private readonly IRedisCache _cache;

    public CacheHandler(IRedisCache cache)
    {
        _cache = cache;
    }
    protected override async Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        HttpResponseMessage response = null;

        response = await base.SendAsync(request, cancellationToken);
        if (!response.IsSuccessStatusCode)
        {
            var options = new JsonSerializerOptions
            {
                WriteIndented = true
            };
            var serResponse = System.Text.Json.JsonSerializer.Serialize(response, options);
            await _cache.Add(request.RequestUri.ToString(), serResponse);
        }
        else
        {
            var byteData = await _cache.Get(request.RequestUri.ToString());
            if (byteData != null)
            {
                var content = Encoding.UTF8.GetString(byteData);
                var httpResponseMessage = System.Text.Json.JsonSerializer.Deserialize<HttpResponseMessage>(content);
                response = httpResponseMessage;
            }
        }
        return response;
    }

}

I can't Deserialize the object that I cached before. It says the object should have parameterless constructor and here HttpResponseMessage doesn't have. I tried too many ways but couldn't.

Any Idea?

1

There are 1 answers

0
Arthur Edgarov On

I don't think you'd be able to deserialize HttpResponseMessage instance, but what you can do is store response data with structure of something like this:

public sealed class HttpResponseMessageMetadata
{
    public int StatusCode { get; set; }

    public object Body { get; set; }
}

After that, you can retrieve this data from the cache, deserialize it and write it as a new response.