How to properly stream response in ASP.NET Core? There is a controller like this (UPDATED CODE):
[HttpGet("test")] public async Task GetTest() { HttpContext.Response.ContentType = "text/plain"; using (var writer = new StreamWriter(HttpContext.Response.Body)) await writer.WriteLineAsync("Hello World"); }
Firefox/Edge browsers show
Hello World
, while Chrome/Postman report an error:
The localhost page isn’t working
localhost unexpectedly closed the connection.
ERR_INCOMPLETE_CHUNKED_ENCODING
P.S. I am about to stream a lot of content, so I cannot specify Content-Length header in advance.
ASP.NET Core SignalR supports streaming from client to server and from server to client. This is useful for scenarios where fragments of data arrive over time. When streaming, each fragment is sent to the client or server as soon as it becomes available, rather than waiting for all of the data to become available.
What is IFormFile. ASP.NET Core has introduced an IFormFile interface that represents transmitted files in an HTTP request. The interface gives us access to metadata like ContentDisposition, ContentType, Length, FileName, and more. IFormFile also provides some methods used to store files.
When the server receives an HTTP request, it processes that request and responds to the client. The response tells the client if the request was successful or not. ASP.NET Core is a web application framework that runs on the server.
The updated Angular project template provides a convenient starting point for ASP.NET Core apps using Angular and the Angular CLI to implement a rich, client-side user interface (UI). The template is equivalent to creating an ASP.NET Core project to act as an API backend and an Angular CLI project to act as a UI.
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" }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With