question

MihaiFloares-4605 avatar image
0 Votes"
MihaiFloares-4605 asked LimitlessTechnology-2700 answered

Why is context.Request.InputStream empty

I saw this question often asked, however I couldn't find solution. Why is the request streal always null. This is the code:

 static void Main(string[] args)
     {
         HttpListener listener = new HttpListener();
         listener.Prefixes.Add("http://localhost:1330/");
         listener.Start();
         while (true)
         {
             HttpListenerContext context = listener.GetContext();
             HttpListenerRequest request = context.Request;
             HttpListenerResponse response = context.Response;
             request.InputStream.Position = 0;
             Console.WriteLine(request.InputStream.Length);
         }
     }

The length is 0 and I tried reading it with stream reader and in a byte array:

 request.InputStream.Position = 0;
 StreamReader reader = new StreamReader(request.InputStream);
 string test = reader.ReadToEnd();
 Console.WriteLine(test);

Or

 request.InputStream.Position = 0;
 byte[] buffer = new byte[10000];
 request.InputStream.Read(buffer, 0, buffer.Length);
 Console.WriteLine(Encoding.UTF8.GetString(buffer));

Both are empty - they just give 7 or 8 ("\n") newlines, I say that because I noticed the console cursor jumps 7 lines below, when a clients connects, without writing any non-blank string.


dotnet-csharpwindows-serverwindows-10-network
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

How are you making the request to the endpoint & what data are you sending as the body of the request?

0 Votes 0 ·
sreejukg avatar image
0 Votes"
sreejukg answered

I think you are using Get method, instead test your web server with Post content. In get method, your input stream will be always empty as there is no data in the body. Try to perform a post request and see whether you are getting the input stream.

Hope this helps.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

LimitlessTechnology-2700 avatar image
0 Votes"
LimitlessTechnology-2700 answered

Hi there,

request.InputStream is always Not null, what you could test is request.InputStream.CanRead && request.InputStream.CanSeek so you can safely re-position the cursor in the stream and later can read it.

Direct reading from the Request.InputStream is dangerous because when re-reading will get null even if the data exists. This is verified in practice.



--If the reply is helpful, please Upvote and Accept it as an answer--

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.