环境:net core 6.0


    1. //这里的流还没有被读取过,直接复制一份CanSeek为false的stream 流 ,进行替换
    2. app.Use(async (context, next) =>
    3. {
    4. // Keep the original stream in a separate
    5. // variable to restore it later if necessary.
    6. var stream = context.Request.Body;
    7. // Optimization: don't buffer the request if
    8. // there was no stream or if it is rewindable.
    9. if (stream == Stream.Null || stream.CanSeek)
    10. {
    11. await next.Invoke();
    12. return;
    13. }
    14. try
    15. {
    16. using (var buffer = new MemoryStream())
    17. {
    18. // Copy the request stream to the memory stream.
    19. await stream.CopyToAsync(buffer);
    20. // Rewind the memory stream.
    21. buffer.Position = 0L;
    22. // Replace the request stream by the memory stream.
    23. context.Request.Body = buffer;
    24. // Invoke the rest of the pipeline.
    25. await next.Invoke();
    26. }
    27. }
    28. finally
    29. {
    30. // Restore the original stream.
    31. context.Request.Body = stream;
    32. }
    33. });