Why is context.Request.InputStream empty

Mihai Floares 1 Reputation point
2022-01-23T22:25:08.063+00:00

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.

Windows for business Windows Client for IT Pros Networking Network connectivity and file sharing
Windows for business Windows Server User experience Other
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Sreeju Nair 12,666 Reputation points
    2022-01-24T10:39:40.457+00:00

    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.

    0 comments No comments

  2. Limitless Technology 39,916 Reputation points
    2022-01-28T08:47:20.413+00:00

    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--

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.