So I have an MVC project. This MVC project contains one controller to which it is necessary to transfer contents back to the client. When streaming begins, it is not possible to determine the length of the content (it is calculated "on the fly"). So I open HttpContext.Current.Response.OutputStream and periodically start recording and Flushing (I already turned off the buffered output and connected the corresponding http headers):
while (some condition){ HttpContext.Current.Response.OutputStream.Write(buffer, 0, buffer.Length); HttpContext.Current.Response.Flush(); }
If I then force the thread to close:
HttpContext.Current.Response.Close();
It does not completely complete the contents of Chunked (it does not append a 0 fragment to the end to indicate EOF to the client).
If I instead close the output stream more gracefully:
HttpContext.Current.Response.End();
OR
HttpContext.Current.ApplicationInstance.CompleteRequest();
It closes the stream correctly (the end of the zero-length end is added), but I get an exception thrown by the application, which indicates that it cannot insert HTTP headers in the output stream, because the stream is already written!
In both cases, the controller continues to return null (or EmptyActionResult).
I assume this exception is caused by the MVC stack requiring each ActionResult to set HTTP headers after the Controller completes. If so, how to implement the Chunked stream in MVC?
Thanks in advance!
EDIT : Excluded exception:
Uncaught Exception: System.Web.HttpException (0x80004005): Server cannot set status after HTTP headers have been sent. at System.Web.Http.WebHost.HttpControllerHandler.EndProcessRequest(IAsyncResult result) at System.Web.Http.WebHost.HttpControllerHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)