0
var bytes = Request.Content.ReadAsByteArrayAsync().Result;

hello, is there any other method that read bytes from content? expect this one

Markus Meyer
  • 3,327
  • 10
  • 22
  • 35

2 Answers2

0

You can also stream the contents into a streamreader https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=net-6.0 This code is from the Microsoft website. You can replace "TestFile.txt" for a stream.

            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt"))
            {
                string line;
                // Read and display lines from the file until the end of
                // the file is reached.
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
Joost00719
  • 716
  • 1
  • 5
  • 20
0

If you want to read content as a string follow code part will help you.

public async Task<string> FormatRequest(HttpRequest request)
    {
        //This line allows us to set the reader for the request back at the beginning of its stream.
        request.EnableRewind();

        var body = request.Body;

        //We now need to read the request stream.  First, we create a new byte[] with the same length as the request stream...
        var buffer = new byte[Convert.ToInt32(request.ContentLength)];

        //...Then we copy the entire request stream into the new buffer.
        await request.Body.ReadAsync(buffer, 0, buffer.Length);

        //We convert the byte[] into a string using UTF8 encoding...
        var bodyAsText = Encoding.UTF8.GetString(buffer);

        //..and finally, assign the read body back to the request body, which is allowed because of EnableRewind()
        request.Body.Seek(0, SeekOrigin.Begin);
        request.Body = body;

        return bodyAsText;
    }
Yusif Karimov
  • 400
  • 5
  • 8
  • technically, `ReadAsync` is not required to copy more than 1 byte; IMO you should loop here, always checking the return value from `ReadAsync` – Marc Gravell Aug 12 '22 at 08:50
  • actually in most cases we set condition for in that code part for 2 kb like this: return Encoding.Unicode.GetByteCount(bodyAsText) <= 2048 ? bodyAsText : "Body size is large than 2 Kb"; – Yusif Karimov Aug 12 '22 at 11:07
  • That changes nothing about ReadAsync – Marc Gravell Aug 14 '22 at 07:38