I have a REST controller that streams the response in csv format using a helper method like below:
public static void CsvStreamHelper(IEnumerable<T> data, Stream stream)
{
using (var writer = new StreamWriter(stream))
{
foreach (var line in data)
{
// format csv lines here
writer.WriteLine(lineString);
}
writer.Flush();
}
}
Then, I'm using this in my Controller like:
public Task<IActionResult> MyController()
{
var data = // Get data here.
CsvStreamHelper(data, this.HttpContext.Response.Body);
return new EmptyResult();
}
This is working fine. However, I would like to use content negotiation middleware with custom formatter like here while continue to stream response.
I can override WriteResponseBodyAsync
method using my helper method. What I'm unsure about is if I use it in my Rest controller like this.Ok(data)
, instead of streaming the response, it will just build the response and send it in one chunk. How can I achieve streaming response with content negotiation middleware?