簡體   English   中英

從請求內容中讀取字節

[英]Read Bytes from Request Content

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

你好,還有其他從內容中讀取字節的方法嗎? 期待這個

您也可以將 stream 的內容放入一個流式閱讀器https://docs.microsoft.com/en-us/dotnet/api/system.ZF98ED07A4D5F50F7DE1410D905F147.7FZ .是從微軟網站閱讀的。 您可以將“TestFile.txt”替換為 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);
                }
            }

如果您想以字符串形式閱讀內容,請按照代碼部分對您有所幫助。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM