Rod Talingting
Rod Talingting

Reputation: 1080

How to write to HttpContext.Response.Body on .NET Core 3.1.x

I've been trying to write or set the HttpContext.Response.Body but to no avail. Most of the samples I found is using the Body.WriteAsync but the paramaters are different than the example. I tried converting my string to byte[] but the text doesn't show on my Response.Body.

Upvotes: 13

Views: 34042

Answers (3)

Tony
Tony

Reputation: 1937

You don't have to call HttpContext.Response.Body.WriteAsync() which requires a byte array. You can pass in a string to HttpContext.Response.WriteAsync()

await HttpContext.Response.WriteAsync("Hello World");

Upvotes: 0

Kirill Osadchuk
Kirill Osadchuk

Reputation: 252

Maybe this is not actual, but as mentioned before you can use the extension method from Microsoft.AspNetCore.Http namespace.

public static Task WriteAsync(this HttpResponse response, string text, CancellationToken cancellationToken = default);

So your code will looks like (this is a bit simpler syntax):

HttpContext.Response.WriteAsync(defaultUnauthorizedResponseHtml);

Upvotes: 3

Fei Han
Fei Han

Reputation: 27793

trying to write or set the HttpContext.Response.Body but to no avail.

You can refer to the following code, which works well for me.

public async Task<IActionResult> Test()
{

    //for testing purpose
    var bytes = Encoding.UTF8.GetBytes("Hello World");

    await HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);

    //...

Besides, you can call HttpResponseWritingExtensions.WriteAsync method to write the given text to the response body.

public async Task<IActionResult> Test()
{
    //for testing purpose
    await Microsoft.AspNetCore.Http.HttpResponseWritingExtensions.WriteAsync(HttpContext.Response, "Hello World");

    //...

Upvotes: 26

Related Questions