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.
How to write to HttpContext.Response.Body on .NET Core 3.1.x
Asked Answered
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");
//...
@Punishment the protected
Empty
property which is a singleton for the EmptyResult
–
Mutation 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);
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");
© 2022 - 2025 — McMap. All rights reserved.
IActionResult
should be used when the action writes directly toResponse.Body
? – Punishment