阅读HTTP请求到Byte数组
我正在开发一个网页,需要采取一个HTTP POST请求,并读入一个字节数组作进一步处理。我有点停留在如何做到这一点,我很为难的是什么做到的最好方式。这里是我的code迄今:
I'm developing a web page that needs to take an HTTP Post Request and read it into a byte array for further processing. I'm kind of stuck on how to do this, and I'm stumped on what is the best way to accomplish. Here is my code so far:
public override void ProcessRequest(HttpContext curContext)
{
if (curContext != null)
{
int totalBytes = curContext.Request.TotalBytes;
string encoding = curContext.Request.ContentEncoding.ToString();
int reqLength = curContext.Request.ContentLength;
long inputLength = curContext.Request.InputStream.Length;
Stream str = curContext.Request.InputStream;
}
}
我检查的要求和等于128现在做我只需要使用一个Stream对象进入它的byte []格式的总字节长度是多少?我在正确的方向前进?不知道如何着手。任何意见将是巨大的。我需要得到整个HTTP请求到的byte []字段。
I'm checking the length of the request and its total bytes which equals 128. Now do I just need to use a Stream object to get it into byte[] format? Am I going in the right direction? Not sure how to proceed. Any advice would be great. I need to get the entire HTTP request into byte[] field.
谢谢!
最简单的方法是将它复制到的MemoryStream
- 然后调用 ToArray的
如果您需要。
The simplest way is to copy it to a MemoryStream
- then call ToArray
if you need to.
如果您正在使用.NET 4中,这是非常简单:
If you're using .NET 4, that's really easy:
MemoryStream ms = new MemoryStream();
curContext.Request.InputStream.CopyTo(ms);
// If you need it...
byte[] data = ms.ToArray();
编辑:如果你不使用.NET 4中,你可以创建自己的实现CopyTo从的。下面是它作为一个扩展方法的一个版本:
If you're not using .NET 4, you can create your own implementation of CopyTo. Here's a version which acts as an extension method:
public static void CopyTo(this Stream source, Stream destination)
{
// TODO: Argument validation
byte[] buffer = new byte[16384]; // For example...
int bytesRead;
while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
{
destination.Write(buffer, 0, bytesRead);
}
}