1. 程式人生 > 其它 >.net Core自定義中介軟體中讀取Request.Body和Response.Body的內容

.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; } }

參照:https://www.cnblogs.com/lwqlun/p/10954936.html