qinchulong
2025-03-29 039a4a5433e7f80adc88b491b549e5d9486e4f9a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
 
namespace WIDESEA_Core.Middleware
{
    public class HttpRequestMiddleware
    {
        public static Func<RequestDelegate, RequestDelegate> Context
        {
            get
            {
                return next => async context =>
                {
 
                    var stream = context.Request.Body;
                    if (stream == Stream.Null || stream.CanSeek)
                    {
                        await next(context);
 
                        return;
                    }
                    try
                    {
                        using (var buffer = new MemoryStream())
                        {
                            // Copy the request stream to the memory stream.
                            await stream.CopyToAsync(buffer);
 
                            // Rewind the memory stream.
                            buffer.Position = 0L;
 
                            // Replace the request stream by the memory stream.
                            context.Request.Body = buffer;
 
                            // Invoke the rest of the pipeline.
                            await next(context);
                        }
                    }
 
                    finally
                    {
                        // Restore the original stream.
                        context.Request.Body = stream;
                    }
 
                };
 
            }
        }
    }
   
}