getting the request body inside HttpContext from a Middleware in asp.net core 2.0

前端 未结 4 1838
礼貌的吻别
礼貌的吻别 2021-02-20 10:45

I am having a simple middleware which fetches the body of the request and store it in a string. It is reading fine the stream, but the issue is it wont call my controller which

4条回答
  •  情深已故
    2021-02-20 11:10

    when it comes to capturing the body of an HTTP request and/or response, this is no trivial effort. In ASP .NET Core, the body is a stream – once you consume it (for logging, in this case), it’s gone, rendering the rest of the pipeline useless.

    Ref:http://www.palador.com/2017/05/24/logging-the-body-of-http-request-and-response-in-asp-net-core/

    public async Task Invoke(HttpContext httpContext)
        {
            var timer = Stopwatch.StartNew();
            string bodyAsText = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
            var injectedRequestStream = new MemoryStream();
            var bytesToWrite = Encoding.UTF8.GetBytes(bodyAsText);
            injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length);
            injectedRequestStream.Seek(0, SeekOrigin.Begin);
            httpContext.Request.Body = injectedRequestStream;
            await _next(httpContext);
    
            timer.Stop();
        }
    

提交回复
热议问题