我正在使用C#的HttpListner制作服务器,服务器正在处理来自传入post请求的二进制数据。我正在尝试创建post请求处理程序,而且由于我正在处理二进制数据,所以我使用的是byte[] (这是我正在读取的缓冲区)。但问题是,在向缓冲区读取任何内容之前,我必须提供缓冲区的长度。我尝试了HttpListnerRequest.InputStream.Length,但它抛出了如下内容:
System.NotSupportedException: This stream does not support seek operations.还有别的方法可以得到溪流的长度吗?其他类似问题的答案只使用StreamReader,但StreamReader不执行二进制操作。
下面是抛出错误的代码。
// If the request is a post request and the request has a body
Stream input = request.InputStream; // "request" in this case is the HttpListnerRequest
byte[] buffer = new byte[input.Length]; // Throws System.NotSupportedException.
input.Read(buffer, 0, input.Length);发布于 2022-07-01 20:50:47
您可以使用HttpListnerRequest.ContentLength64,它表示请求体的长度,在本例中是输入流。示例:
// If the request is a post request and the request has a body
long longLength = request.ContentLength64;
int length = (int) longLength;
Stream input = request.InputStream; // "request" in this case is the HttpListnerRequest
byte[] buffer = new byte[length];
input.Read(buffer, 0, length);https://stackoverflow.com/questions/72834510
复制相似问题