Search code examples
c#asp.net-core-webapimemorystream

InvalidOperationException: Timeouts are not supported on this stream


I am trying to read file as a stream in 1 MB chunks. So that load time of the file is better at frontend. But I get below error at backend while trying to do so. Would appreciate your input.

I get below error in the controller:

System.InvalidOperationException: Timeouts are not supported on this stream.
   at System.IO.Stream.get_ReadTimeout()
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)

itemController: (Writeline below returns ApplicationName.Shared.ITEMStreamBlock)

   var result = await itemRepository.GetFile(fileName, offset, blobLengthRemaining);
   System.Diagnostics.Debug.WriteLine(result); // here it returns ApplicationName.Shared.ITEMStreamBlock
   return result;
    

Solution

  • Interestingly enough, this happens when you try to return a stream as json (which implicitly happens).

    Don't return your object with a memory stream on it. You can maybe return it as a content-stream by setting the content type to application/octet-stream and returning a FileStreamResult?

    Example:

    [HttpGet]
    public FileStreamResult GetTest()
    {
      var stream = // your stream
      return new FileStreamResult(stream, new MediaTypeHeaderValue("application/octet-stream"))
      {
        FileDownloadName = "test.txt"
      };
    }
    

    Otherwise, what you can do is return a byte[] for the section that you want to return instead of just a memory stream. Just don't try to serialize a stream to json by having a property of that type.