Search code examples
servicestackservicestack-textservicestack-bsd

ToOptimizedResult on an HttpResult causes a StackOverflow exception


I'm using v3.9.56.0 and I'm encountering a stack overflow exception when I call ToOptimizedResult (Called from my own service runner) on a returned HttpResult from a service. When I dig deeper I found the exception was coming from the JsonSerializer.

Here is the snippet of code for what is being returned:

return new HttpResult(new FileInfo(Path.Combine(path, file)), true)

Solution

  • This is happening because ToOptimizedResult expects to receive a DTO response object that it can compress to create a CompressedResult response.

    However you are providing an HttpResult which effectively is wrapper for the byte[]/string DTO response object of the file you are loading, this wrapper is a complex type, and isn't really what you want to be trying to optimise.

    If your file is binary then you should return the byte[] of the contents, if it is plain text then return a string. Then the ToOptimizedResult can optimise that data.

    // Binary file type
    return File.ReadAllBytes(Path.Combine(path, file));  // returns byte[]
    
    // Plain text file type
    return File.ReadAllText(Path.Combine(path, file));  // returns string