1 Answer
1

What's the added value of using OutputFormatterWriteContext.WriterFactory instead of a regular StreamWriter, which works just fine in this case?

Actually, you could write to HttpResponse.Body directly if you like. The point is, as the document describes, don't use WriterFactory when you want to write binary data.

The ASP.NET Core uses the HttpResponseStreamWriter to write stream behind the scenes (See MemoryPoolHttpResponseStreamWriterFactory)
. This implementation exposes several methods which are quite similar to StreamWriter. But the HttpResponseStreamWriter uses ArrayPool<> behind the hood. According to this document, it should improve performance when arrays are created and destroyed frequently.

My main questions is why the BOM not output when using OutputFormatterWriteContext.WriterFactory?

/// <summary<
/// Writes to the using the supplied .
/// It does not write the BOM and also does not close the stream.
/// </summary<
public class HttpResponseStreamWriter : TextWriter
{
private const int MinBufferSize = 128;
internal const int DefaultBufferSize = 16 * 1024;
...
}

Is there a way to avoid explicitly writing the BOM, e.g. have a writer calling Encoding.GetPreamble() automatically?

If you're using the built-in OutputFormatterWriteContext.WriterFactory, I believe the answer is YES. You need to write the BOM header by your self if you wish.

Lastly, you should not write headers within the WriteResponseBodyAsync() method. That's a duty of WriteResponseHeaders(ctx). It's better to move this codes to WriteResponseHeaders(OutputFormatterWriteContext ctx ):

That's because the HttpResponseStreamWriter doesn't write BOM at all : But I write BOM manually directly to response.Body before even getting to WriterFactory. What happens to that?
– Leon VMay 22 '19 at 8:39

@LeonV In that case, the BOM will be written to the stream. But note that is not done by HttpResponseStreamWriter automatically, but by the Body stream (Stream.Write()). Actually, if you look at the final code I post above, it works in the way as you describe.
– itminusMay 22 '19 at 8:43

If you're using the built-in OutputFormatterWriteContext.WriterFactory, I believe the answer is YES. You need to write the BOM header by your self if you wish. Well, this is exactly what I do - write BOM by myself. The question is if there is a way to avoid it.
– Leon VMay 22 '19 at 8:44

@LeonV No way if you using the built-in OutputFormatterWriteContext.WriterFactory unless you do it manually. The StreamWriter will do that.
– itminusMay 22 '19 at 8:46

Your final code is very similar to mine, aside from writing headers in a separate method and does NOT produce BOM. That was the essence of my question.
– Leon VMay 22 '19 at 8:52