My MVC/webApi calculates a report to be returned in a file as a stream. The calculation takes quite some time so in order to speed up the user experience it's cached. When it's returned the stream is automatically disposed. So in order to get the caching working it has to be copied over to a new Stream object every time.
Since I want to cache the outcome I don't want it to be disposed at all.
I don't know how the file could be cached through configuration because it's not a file on disk, it's calculated on demand based on input.
So how can MVC/WebApi be configured to not automatically dispose this response? It might be with the OutgoingResponseContext, but can't find anything in there that might do that.
Edit, added code so far: Code for returning a stream, deep copying it every time it would otherwise be passed as reference and returning it as a file.
public stream ConfigureResponseHeadersForFileStream(string input)
{
// Calculate file
var result = new CachedFile(input, CalculateFileContent());
WebOperationContext.Current.OutgoingResponse.Headers.Clear();
WebOperationContext.Current.OutgoingResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
WebOperationContext.Current.OutgoingResponse.ContentLength = length;
WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "attachment; filename=" + "input");
_cacher.Add(result);
return result.Content;
}
public class CachedFile
{
private Stream _content;
public string Input;
public long Length
{
get
{
return _content.Length;
}
}
/// <summary>
/// Will be copied into a new caching object.
/// Because the web environment will dispose the stream that's returned to the user.
/// </summary>
public Stream Content
{
get
{
var stream = new MemoryStream();
_content.CopyTo(stream);
return stream;
}
set
{
_content = new MemoryStream();
value.CopyTo(_content);
}
}
public CachedFile(string input, Stream content)
{
Input = input;
Content = content;
}
}