ToOptimizedResultUsingCache with Gateway.Send

Hello!

I would like to call internal or external services (through Consul) from a service method with the Gateway.Send but I get InvalidCastException if I use the ToOptimizedResultUsingCache.
I read this post InvalidCastException, getting back ServiceStack.CompressedResult instead of data but I don’t know how to use it with external services.

Thank you,
Tom

You can’t call a Service Gateway using ToOptimizedResultUsingCache since it returns the compressed byte[] on cached requests whereas the Service Gateway needs access to the unserialized Response DTO. If you use the newer [CacheResponse] Attribute it wont return compressed byte[] responses for Service Gateway requests.

Does this hold true for ToOptimizedResult?

I’ve added the [CacheResponse] attribute to the service method but calling via Gateway.Send is throwing the InvalidCastException as in the first post.

inside Razor view:

var metrics = Gateway.Send(new GetMetrics
    {
        ByHour = true,
        ByDate = true,
        ByCategory = true,
        BeginDate = DateTime.Today,
        EndDate = DateTime.Today
    });	

Service Implementation:

[CacheResponse]
        public object Get(GetMetrics request)
        {

            var cfg = new ReportQueryConfig
            {
                BeginDate = request.BeginDate,
                EndDate = request.EndDate,
                etc.
				
            };

            var dtos = GetData(cfg);

            return Request.ToOptimizedResult(dtos);
        }

It applies to all ToOptimizedResult APIs for reasons above.

Don’t use the [CacheResponse] attribute with ToOptimizedResult, just use one or the other and if you want to be able to call it via the Gateway you cant use the ToOptimizedResult APIs.

Ah, makes sense now. I read you previous reply as use the CacheResponse attribute in addition to using ToOptimized…

Then I re-read the docs and it became clear:

When only specifying a Duration=60 ServiceStack only caches the Server Response so it behaves similar to using the existing ToOptimizedResult() API

2 Likes