【发布时间】:2020-05-04 02:44:13
【问题描述】:
我有一个中间件来跟踪我在 ASP.NET Core 2.2 API 中自定义开发的网关的性能。我使用了 StackOverflow 中的 this post。
基本上主要部分如下:
public class ResponseRewindMiddleware {
private readonly RequestDelegate next;
public ResponseRewindMiddleware(RequestDelegate next) {
this.next = next;
}
public async Task Invoke(HttpContext context) {
Stream originalBody = context.Response.Body;
/* MY CODE COMES HERE */
try {
using (var memStream = new MemoryStream()) {
context.Response.Body = memStream;
await next(context);
memStream.Position = 0;
string responseBody = new StreamReader(memStream).ReadToEnd();
memStream.Position = 0;
await memStream.CopyToAsync(originalBody);
}
} finally {
context.Response.Body = originalBody;
}
}
此代码运行正常。但我想将输入(JSON 正文)记录到网关并添加以下行:
using (System.IO.StreamReader rd = new System.IO.StreamReader(context.Request.Body))
{
bodyStr = rd.ReadToEnd();
}
这会从 Request 中读取输入正文,但流程已中断,并且流程的其余部分没有流程,从而导致“HTTP 500 内部服务器错误”。我假设通过 Stream 读取请求正文会破坏某些内容。
如何在不中断流程的情况下读取请求正文?
【问题讨论】:
-
为什么要用
using(){....}包裹读者?超出范围时,它将处理 Request.Body。此外,您忘记将 Body 流倒回到位置 0? -
也许你可以参考How to read request body in a asp.net core webapi controller?,特别是如果你多次读取请求流,你应该使用EnableBuffering
标签: asp.net-core middleware gateway