0

In ASP.NET one has three options (that I know of) for writing directly to the response buffer.

Given the following data:

var str = "Hello World";
var bytes = Encoding.UTF8.GetBytes(str);

We can write to the response buffer using:

// method 1
await HttpResponse.WriteAsync(str);
// method 2
await HttpResponse.Body.WriteAsync(bytes);
// method 3
await HttpResponse.BodyWriter.WriteAsync(bytes);

What are the differences between them, if any?

0

1 Answer 1

1

Well, HttpResponse.WriteAsync is actually an extension method, and the current implementation uses the body writer underneath. So it's equivalent to using BodyWriter.WriteAsync. It also does some additional work beforehand, such as starting the response if you didn't already call StartAsync.

So that leaves us with Body.WriteAsync. Body is a stream, unlike BodyWriter, which is a pipeline. As the documentation states:

Pipelines are recommended over streams. Streams can be easier to use for some simple operations, but pipelines have a performance advantage and are easier to use in most scenarios.

Since streams were there first, it's still supported. But they want you to use pipelines. Streams are easier to use, however, especially for simple scenarios.

So, your pick.

Not the answer you're looking for? Browse other questions tagged or ask your own question.