0

I am writing a controller that returns lines of text from a file, and I want to stream them using IAsyncEnumerable. If I do that, all the strings are returned in the response in a single line of text - this is not particularly friendly to the consumer.

As an example, if I have this:

    [HttpGet]
    public async IAsyncEnumerable<string> GetAsync() {
        for (var i = 0; i < 3; i++) {
            yield return i.ToString();
        }
    }

I get a response that looks like ["0","1","2"], but I'd prefer to return something like:

"0"
"1"
"2"

I'm new to AsyncEnumerables in ASP.NET core, but my (possibly wrong) understanding is that if I were to use a TextOutputFormatter I would wind up having to enumerate it in the formatter and that wouldn't be streaming to the client anymore. I tried manually adding Environment.NewLine to the end of the strings, but it just gets encoded in the string, the response doesn't actually contain line breaks.

Is there a good way to do this?

Aaron Whittier
  • 233
  • 1
  • 2
  • 8
  • 1
    You get that output because (presumably) the result is being formatted as a JSON array. This is only indirectly related to `IAsyncEnumerable`. What happens if, in your client request, you use an `Accept` header set to `text/plain`? – Jeroen Mostert Sep 28 '22 at 19:59
  • The response is still returned as content type `application/json`, interestingly enough. If I put `[Produces("text/plain")]` on my controller, I get an error that there isn't a formatter for `text/plain` - so it looks like I need a formatter regardless since I would prefer it not returned as a JSON array. – Aaron Whittier Sep 28 '22 at 20:33
  • 1
    Have a look at [Custom formatters in ASP.NET Core Web API](https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/custom-formatters?view=aspnetcore-6.0). Try to custom an output formatter class. – Qing Guo Sep 29 '22 at 09:58

0 Answers0