How to stream with ASP.NET Core
I was wondering as well how to do this, and have found out that
the original question's code actually works OK on ASP.NET Core 2.1.0-rc1-final
, neither Chrome (and few other browsers) nor JavaScript application do not fail with such endpoint.
Minor things I would like to add are just set StatusCode and close the response Stream to make the response fulfilled:
[HttpGet("test")]
public void Test()
{
Response.StatusCode = 200;
Response.ContentType = "text/plain";
using (Response.Body)
{
using (var sw = new StreamWriter(Response.Body))
{
sw.Write("Hi there!");
}
}
}
To stream a response that should appear to the browser like a downloaded file, you should use FileStreamResult
:
[HttpGet]
public FileStreamResult GetTest()
{
var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World"));
return new FileStreamResult(stream, new MediaTypeHeaderValue("text/plain"))
{
FileDownloadName = "test.txt"
};
}
@Developer4993 was correct that to have data sent to the client before the entire response has been parsed, it is necessary to Flush
to the response stream. However, their answer is a bit unconventional with both the DELETE
and the Synchronized.StreamWriter
. Additionally, Asp.Net Core 3.x will throw an exception if the I/O is synchronous.
This is tested in Asp.Net Core 3.1:
[HttpGet]
public async Task Get()
{
Response.ContentType = "text/plain";
StreamWriter sw;
await using ((sw = new StreamWriter(Response.Body)).ConfigureAwait(false))
{
foreach (var item in someReader.Read())
{
await sw.WriteLineAsync(item.ToString()).ConfigureAwait(false);
await sw.FlushAsync().ConfigureAwait(false);
}
}
}
Assuming someReader
is iterating either database results or some I/O stream with a large amount of content that you do not want to buffer before sending, this will write a chunk of text to the response stream with each FlushAsync()
.
For my purposes, consuming the results with an HttpClient
was more important than browser compatibility, but if you send enough text, you will see a chromium browser consume the results in a streaming fashion. The browser seems to buffer a certain quantity at first.
Where this becomes more useful is with the latest IAsyncEnumerable
streams, where your source is either time or disk intensive, but can be yielded a bit at at time:
[HttpGet]
public async Task<EmptyResult> Get()
{
Response.ContentType = "text/plain";
StreamWriter sw;
await using ((sw = new StreamWriter(Response.Body)).ConfigureAwait(false))
{
await foreach (var item in GetAsyncEnumerable())
{
await sw.WriteLineAsync(item.ToString()).ConfigureAwait(false);
await sw.FlushAsync().ConfigureAwait(false);
}
}
return new EmptyResult();
}
You can throw an await Task.Delay(1000)
into either foreach
to demonstrate the continuous streaming.
Finally, @StephenCleary 's FileCallbackResult
works the same as these two examples as well. It's just a bit scarier with the FileResultExecutorBase
from deep in the bowels of the Infrastructure
namespace.
[HttpGet]
public IActionResult Get()
{
return new FileCallbackResult(new MediaTypeHeaderValue("text/plain"), async (outputStream, _) =>
{
StreamWriter sw;
await using ((sw = new StreamWriter(outputStream)).ConfigureAwait(false))
{
foreach (var item in someReader.Read())
{
await sw.WriteLineAsync(item.ToString()).ConfigureAwait(false);
await sw.FlushAsync().ConfigureAwait(false);
}
}
outputStream.Close();
});
}
It is possible to return null
or EmptyResult()
(which are equivalent), even when previously writing to Response.Body
. It may be useful if the method returns ActionResult
to be able to use all the other results aswell (e.g. BadQuery()
) easily.
[HttpGet("test")]
public ActionResult Test()
{
Response.StatusCode = 200;
Response.ContentType = "text/plain";
using (var sw = new StreamWriter(Response.Body))
{
sw.Write("something");
}
return null;
}