Some third party is posting data to our webpage via HTTP Post. I want to set a limit say 1 Kb for HTTP posts, if it is above 1 Kb I need to reject the HTTP post. I don't want to read the whole request stream to find out the content length. Is there anyway I can validate without reading the entire request stream?
Asked
Active
Viewed 677 times
1 Answers
2
It depends whether the content length is in the headers or not. If it is, you can just fetch that (e.g. HttpRequest.ContentLength
). However, they don't have to specify that.
Otherwise, you could just read the first 1K and 1 extra byte:
byte[] data = new byte[1025];
int length = 0;
using (var stream = request.GetBufferlessInputSream())
{
while (length < validData.Length)
{
int bytesRead = stream.Read(data, length, data.Length - length);
if (bytesRead == 0)
{
break;
}
length += bytesRead;
}
}
if (length > 1024)
{
// Client sent more than 1024 bytes of data!
}
// Otherwise, use the first "length" bytes of data
Note that data
has a size of 1025 so that we try to read one more byte than we're allowing the client to send.
If the client has sent more than 1K, we'll still read the first 1K - but we'll only read a single unnecessary byte. We won't keep reading forever.

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194