Home > Enterprise >  Read Bytes from Request Content
Read Bytes from Request Content

Time:08-12

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

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

CodePudding user response:

You can also stream the contents into a streamreader https://docs.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);
                }
            }

CodePudding user response:

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;
    }
  • Related