Search code examples
asp.net-coreasp.net-core-webapihttpresponse

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 then the example. I tried converting my string to byte[] but the text doesn't show on my Response.Body.


Solution

  • 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");
    
        //...