Asp.net core 3.0 how to read and write body using PipeWriter RRS feed

  • Question

  • User-2103114970 posted


    Could you please help me i am writing middleware for request and response .

    i was using  stream but need to convert  PipeWriter and PipeReader.

    Could you please help me how read body from PipeWriter .

    i have written code for PipeReader.

    private  async Task<string> GetStringFromPipeReader(PipeReader reader)
                StringBuilder stringBuilder = new StringBuilder();
                while (true)
                    // await some data being available
                    ReadResult read = await reader.ReadAsync();
                    ReadOnlySequence<byte> buffer = read.Buffer;
                    // check whether we've reached the end
                    // and processed everything
                    if (buffer.IsEmpty && read.IsCompleted)
                        break; // exit loop
                    // process what we received
                    foreach (var segment in buffer)
                        string asciString = Encoding.ASCII.GetString(
                    // tell the pipe that we used everything
                   // reader.AdvanceTo(buffer.End);

                    reader.AdvanceTo(buffer.Start, buffer.End);

                    if (read.IsCompleted)

                return Convert.ToString(stringBuilder);

           private  async Task  WriteSomeDataAsync(PipeWriter writer, string jsonValue)
                // use an oversized size guess
                Memory<byte> workspace = writer.GetMemory();
                // write the data to the workspace
                int bytes = Encoding.ASCII.GetBytes(
                   jsonValue, workspace.Span);
                // tell the pipe how much of the workspace
                // we actually want to commit
                // this is **not** the same as Stream.Flush!
                await writer.FlushAsync();


    Wednesday, October 16, 2019 3:52 PM

All replies

  • User753101303 posted


    You tried https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/request-response?view=aspnetcore-3.0 ?

    Also please never post code without telling what explicitly what happens. It's not uncommon to spot multiple possible issues and then we have to gig deeper to guess which is the current problem you may have and sometimes it turns out to be something that couldn't be even guessed from the code...

    Meanwhile telling us what happens take 30 seconds of extra time.

    Wednesday, October 16, 2019 6:55 PM
  • User-2103114970 posted


    Thanks for your reply, i can able to read  body from httpRequest using PipeReader , is there any way to read body from HttpResponse using pipeWriter.



    Thursday, October 17, 2019 6:43 PM