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 Server
Windows Server
A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.
8,837 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
7,561 questions
Windows 10 Network
Windows 10 Network
Windows 10: A Microsoft operating system that runs on personal computers and tablets.Network: A group of devices that communicate either wirelessly or via a physical connection.
2,000 questions
{count} votes

2 answers

Sort by: Most helpful
  1. sreejukg 9,746 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.

  2. Limitless Technology 37,526 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--