So I have an MVC project. This MVC project contains one Controller, that needs to stream content back to the client. When the streaming starts, there is no way to determine the content length (it is calculated on-the-fly). So I open HttpContext.Current.Response.OutputStream, and start writing and Flushing periodically (I've already disabled buffered output, and attached the appropriate http headers):
while (some condition){
HttpContext.Current.Response.OutputStream.Write(buffer, 0, buffer.Length);
HttpContext.Current.Response.Flush();
}
If I then force the stream to close:
HttpContext.Current.Response.Close();
It does not properly end the Chunked content (it does not append a 0 length chunk at 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 properly closes the stream (zero length chunk appended to end), but I get an exception thrown by the application, indicating that it can't insert HTTP headers into the output stream, because the stream was already written!
In both cases, the Controller goes on to return null (or EmptyActionResult).
I assume the exception is caused because the MVC stack requires that every ActionResult set HTTP headers after the Controller finishes executing. If this is the case, how does one implement a Chunked stream in MVC?
Thanks in advance!
EDIT: The exact exception being thrown is:
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)