如何在 .NET Core 3 上写入 HttpContext.Response.Body。1.x
How to write to HttpContext.Response.Body on .NET Core 3.1.x
我一直在尝试编写或设置 HttpContext.Response.Body 但无济于事。我发现的大多数样本都使用 Body.WriteAsync 但参数与示例不同。我尝试将我的字符串转换为 byte[],但文本没有显示在我的 Response.Body.
上
trying to write or set the HttpContext.Response.Body but to no avail.
你可以参考下面的代码,对我来说效果很好
public async Task<IActionResult> Test()
{
//for testing purpose
var bytes = Encoding.UTF8.GetBytes("Hello World");
await HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
//...
此外,您可以调用HttpResponseWritingExtensions.WriteAsync
method将给定的文本写入响应正文。
public async Task<IActionResult> Test()
{
//for testing purpose
await Microsoft.AspNetCore.Http.HttpResponseWritingExtensions.WriteAsync(HttpContext.Response, "Hello World");
//...
也许这不是实际的,但如前所述,您可以使用 Microsoft.AspNetCore.Http 命名空间中的扩展方法。
public static Task WriteAsync(this HttpResponse response, string text, CancellationToken cancellationToken = default);
所以你的代码看起来像(这是一个更简单的语法):
HttpContext.Response.WriteAsync(defaultUnauthorizedResponseHtml);
我一直在尝试编写或设置 HttpContext.Response.Body 但无济于事。我发现的大多数样本都使用 Body.WriteAsync 但参数与示例不同。我尝试将我的字符串转换为 byte[],但文本没有显示在我的 Response.Body.
上trying to write or set the HttpContext.Response.Body but to no avail.
你可以参考下面的代码,对我来说效果很好
public async Task<IActionResult> Test()
{
//for testing purpose
var bytes = Encoding.UTF8.GetBytes("Hello World");
await HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
//...
此外,您可以调用HttpResponseWritingExtensions.WriteAsync
method将给定的文本写入响应正文。
public async Task<IActionResult> Test()
{
//for testing purpose
await Microsoft.AspNetCore.Http.HttpResponseWritingExtensions.WriteAsync(HttpContext.Response, "Hello World");
//...
也许这不是实际的,但如前所述,您可以使用 Microsoft.AspNetCore.Http 命名空间中的扩展方法。
public static Task WriteAsync(this HttpResponse response, string text, CancellationToken cancellationToken = default);
所以你的代码看起来像(这是一个更简单的语法):
HttpContext.Response.WriteAsync(defaultUnauthorizedResponseHtml);