C#C
C#3y ago
Novruz

❔ HttpContext reading Request and Response body

I use serilog for my logging system. My aim is that converting Request body and response body to string and logging them as a string to my log file.

There is no problem with Request Body. But When it comes to Response Body, the method in this pictur return "" as a string. Just emtpy.

So i asked to ChatGPT. It gives me that

private string GetResponseBodyAsString(HttpContext context)
        {
            context.Response.Body.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(context.Response.Body, Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }


This code When I use this code. There is exception that says Specified method is not supported.

When I dlete that line. I got new error that says Stream does not support reading

So ChatGPT gave me totally new class and new method logic that

  public class ResponseCaptureStream : Stream
    {
        private readonly Stream _originalStream;
        private readonly MemoryStream _captureStream;

        public ResponseCaptureStream(Stream originalStream)
        {
            _originalStream = originalStream;
            _captureStream = new MemoryStream();
        }

        public string GetCapturedContent()
        {
            _captureStream.Seek(0, SeekOrigin.Begin);
            using var reader = new StreamReader(_captureStream, Encoding.UTF8);
            return reader.ReadToEnd();
        }

        public override bool CanRead => true;
        public override bool CanSeek => false;
        public override bool CanWrite => false;
        public override long Length => throw new NotSupportedException();
        public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
        public override void Flush() => _originalStream.Flush();
        public override int Read(byte[] buffer, int offset, int count) => _originalStream.Read(buffer, offset, count);
        public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
        public override void SetLength(long value) => throw new NotSupportedException();
        public override void Write(byte[] buffer, int offset, int count) => _captureStream.Write(buffer, offset, count);
    }



For this method

 private async Task<string> GetResponseBodyAsStringAsync(this HttpContext context)
    {
        var originalResponseBody = context.Response.Body;
        using var captureStream = new ResponseCaptureStream(originalResponseBody);
        context.Response.Body = captureStream;

        await _next(context);

        context.Response.Body = originalResponseBody; // Restore the original response body

        return captureStream.GetCapturedContent();
    }
Screenshot_2023-08-25_201629.png
Was this page helpful?