Reputation: 1080
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
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
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
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