如何使用 PipeWriter 读取和更新 HttpResponse 正文?



这实际上是一个与.net core 3.0直接相关的两部分问题,特别是与PipeWriter相关的问题: 1(我应该如何在HttpResponse正文中阅读? 2( 如何更新 HttpResponse?我问这两个问题是因为我觉得解决方案可能涉及相同的理解和代码。

以下是我如何在 .net core 2.2 中工作 - 请注意,这是使用流而不是 PipeWriter 以及与流相关的其他"丑陋"的东西 - 例如。MemoryStream、Seek、StreamReader 等

public class MyMiddleware
{
private RequestDelegate Next { get; }
public MyMiddleware(RequestDelegate next) => Next = next;
public async Task Invoke(HttpContext context)
{
var httpResponse = context.Response;
var originalBody = httpResponse.Body;
var newBody = new MemoryStream();
httpResponse.Body = newBody;
try
{
await Next(context);
}
catch (Exception)
{
// In this scenario, I would log out the actual error and am returning this "nice" error
httpResponse.StatusCode = StatusCodes.Status500InternalServerError;
httpResponse.ContentType = "application/json"; // I'm setting this because I might have a serialized object instead of a plain string
httpResponse.Body = originalBody;
await httpResponse.WriteAsync("We're sorry, but something went wrong with your request.");
return;
}
// If everything worked
newBody.Seek(0, SeekOrigin.Begin);
var response = new StreamReader(newBody).ReadToEnd(); // This is the only way to read the existing response body
httpResponse.Body = originalBody;
await context.Response.WriteAsync(response);
}
}

使用PipeWriter将如何工作?例如。似乎使用管道而不是底层流更可取,但我还找不到任何关于如何使用它来替换我上面的代码的示例?

是否存在我需要等待流/管道完成写入才能将其读回和/或将其替换为新字符串的情况?我个人从未这样做过,但是查看PipeReader的示例似乎表明要以块的形式读取内容并检查IsComplete。

更新 HttpRepsonse 是

private  async Task WriteDataToResponseBodyAsync(PipeWriter writer, string jsonValue)
{
// use an oversized size guess
Memory<byte> workspace = writer.GetMemory();
// write the data to the workspace
int bytes = Encoding.ASCII.GetBytes(
jsonValue, workspace.Span);
// tell the pipe how much of the workspace
// we actually want to commit
writer.Advance(bytes);
// this is **not** the same as Stream.Flush!
await writer.FlushAsync();
}

最新更新