[英]Read Bytes from Request Content
var bytes = Request.Content.ReadAsByteArrayAsync().Result;
hello, is there any other method that read bytes from content?你好,还有其他从内容中读取字节的方法吗? expect this one期待这个
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.您也可以将 stream 的内容放入一个流式阅读器https://docs.microsoft.com/en-us/dotnet/api/system.ZF98ED07A4D5F50F7DE1410D905F147.7FZ .是从微软网站阅读的。 You can replace "TestFile.txt" for a stream.您可以将“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);
}
}
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.