.net Core自定义中间件中读取Request.Body和Response.Body的内容?
1 .Net Core 2.X时代
public IActionResult Index() { Request.EnableRewind(); using (var reader = new StreamReader(Request.Body)) { var body = reader.ReadToEnd(); // Do something Request.Body.Seek(0, SeekOrigin.Begin); body = reader.ReadToEnd(); } // More code return View("Index"); }
2 .NET Core 3.0时代
public class SignatureMiddleware { private readonly RequestDelegate _next; public SignatureMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { //启用读取request context.Request.EnableBuffering(); //变量设置 var request = context.Request; var response = context.Response; //请求body using var requestReader = new StreamReader(request.Body); var requestBody = await requestReader.ReadToEndAsync(); request.Body.Position = 0; //设置stream存放ResponseBody var responseOriginalBody = response.Body; using var memStream = new MemoryStream(); response.Body = memStream; // 执行其他中间件 await _next(context); //处理执行其他中间件后的ResponseBody memStream.Position = 0; var responseReader = new StreamReader(memStream); var responseBody = await responseReader.ReadToEndAsync(); memStream.Position = 0; await memStream.CopyToAsync(responseOriginalBody); response.Body = responseOriginalBody; } }