Your bug lies in the following line:
byte b = (byte)ss.ReadByte(); The byte type is unsigned; when Stream.ReadByte returns -1 at the end of the stream, you’re indiscriminately casting it to byte, which converts it to 255 and, therefore, satisfies the b >= 0 condition. It is helpful to note that the return type is int, not byte, for this very reason.
A quick-and-dirty fix for your code:
List<byte> bb = new List<byte>(); var ss = context.Request.InputStream; int next = ss.ReadByte(); while (next != -1) { bb.Add((byte)next); next = ss.ReadByte(); } The following solution is more efficient, since it avoids the byte-by-byte reads incurred by the ReadByte calls, and uses a dynamically-expanding byte array for Read calls instead (similar to the way that List<T> is internally implemented):
var ss = context.Request.InputStream; byte[] buffer = new byte[1024]; int totalCount = 0; while (true) { int currentCount = ss.Read(buffer, totalCount, buffer.Length - totalCount); if (currentCount == 0) break; totalCount += currentCount; if (totalCount == buffer.Length) Array.Resize(ref buffer, buffer.Length * 2); } Array.Resize(ref buffer, totalCount);