C# MemoryStream - Timeouts are not supported on this stream

30,095

Api is trying to serialize the MemoryStream to json. So, would you try to change ContentType;

    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("export-to-csv")]
    public FileStreamResult ExportDeposits([FromUri(Name = "")]DepositSearchParamsVM depositSearchParamsVM)
    {
        if (depositSearchParamsVM == null)
        {
            depositSearchParamsVM = new DepositSearchParamsVM();
        }
        var records = _DepositsService.SearchDeposits(depositSearchParamsVM);
        var result = _DepositsService.WriteCsvToMemory(records);
        var memoryStream = new MemoryStream(result);
        Response.ContentType = new MediaTypeHeaderValue("application/octet-stream").ToString();// Content type
        return new FileStreamResult(memoryStream, "text/csv") { FileDownloadName = "export.csv" };
    }
Share:
30,095

Related videos on Youtube

Jim Kiely
Author by

Jim Kiely

Updated on January 02, 2020

Comments

  • Jim Kiely
    Jim Kiely over 4 years

    I'm trying to create a csv file dynamially and output the stream to the browser.

    Here is my api end point:

        [System.Web.Http.HttpGet]
        [System.Web.Http.Route("export-to-csv")]
        public FileStreamResult ExportDeposits([FromUri(Name = "")]DepositSearchParamsVM depositSearchParamsVM)
            {
                if (depositSearchParamsVM == null)
                {
                    depositSearchParamsVM = new DepositSearchParamsVM();
                }
                var records = _DepositsService.SearchDeposits(depositSearchParamsVM);
                var result = _DepositsService.WriteCsvToMemory(records);
                var memoryStream = new MemoryStream(result);
    
                return new FileStreamResult(memoryStream, "text/csv") { FileDownloadName = "export.csv" };
        }
    

    Here is my service method:

    public byte[] WriteCsvToMemory(IEnumerable<DepositSummaryVM> records)
            {
                using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                using (var writer = new StreamWriter(stream))
                using (var csv = new CsvWriter(writer))
                {
                    csv.WriteRecords(records);
                    writer.Flush();
                    stream.Position = 0;
                    var text = reader.ReadToEnd();
    
                    return stream.ToArray();
    

    }

        }
    

    Here is the error message:

    { "message": "An error has occurred.", "exceptionMessage": "Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.",
    "exceptionType": "Newtonsoft.Json.JsonSerializationException",
    "stackTrace": " at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Owin.HttpMessageHandlerAdapter.d__13.MoveNext()", "innerException": { "message": "An error has occurred.", "exceptionMessage": "Timeouts are not supported on this stream.", "exceptionType": "System.InvalidOperationException", "stackTrace": " at System.IO.Stream.get_ReadTimeout()\r\n at GetReadTimeout(Object )\r\n at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)" } }

    • jdweng
      jdweng over 6 years
      Http uses TCP as the transport layer.The error is coming from the TCP layer.TCP is reliable because every datagram (max 1500 bytes) gets an ACK.If an ACK is not received usually the datagram is sent up to three times. So for some reason the ACK is not occurring.So the first question is when does the error occur?Is when the connection is first made or after some data is received (and how much data is received)? The best way of debugging these issues is to use a sniffer like wireshark or fiddler.Start by looking at the http messages.Each TCP message will be composed of one or moreTCP packets.
    • jdweng
      jdweng over 6 years
      A common reason for this type error is the http mode. Http 1.0 is stream mode while http 1.1 is chunk mode. Http 1.1 requires the client to send a next chunk message and when it is not sent a time out will occur. So using a sniffer you can look at the headers to see what http mode is being used. At the end of each http message there is a status normally 200 done when complete. 100 is continue. 400 - 500 are errors. So to fix normally you need to send on 1st request a header to indicate that you want to use http 1.0 instead of 1.1.
    • Jim Kiely
      Jim Kiely over 6 years
      I solved this by referencing this: stackoverflow.com/questions/26038856/…