Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stream with ASP.NET Core

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.

like image 969
Dmitry Nogin Avatar asked Mar 13 '17 18:03

Dmitry Nogin


People also ask

What is stream in ASP.NET Core?

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 C#?

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.

What is HTTP request and Httpresponse in asp net?

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.

Can you use angular with .NET Core?

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.


1 Answers

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"   }; } 
like image 72
Stephen Cleary Avatar answered Sep 19 '22 20:09

Stephen Cleary