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

3

13

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.

Overskirt answered 10/7, 2020 at 12:6 Comment(0)
A
25

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");

    //...
Arbutus answered 13/7, 2020 at 3:32 Comment(2)
Which IActionResult should be used when the action writes directly to Response.Body?Punishment
@Punishment the protected Empty property which is a singleton for the EmptyResultMutation
F
3

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);
Fumble answered 5/12, 2020 at 17:18 Comment(0)
F
0

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");
Fifteenth answered 27/6, 2024 at 22:11 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.