Why is context.Request.InputStream empty

Mihai Floares 1 Reputation point

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();
        while (true)
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;
            request.InputStream.Position = 0;

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();


request.InputStream.Position = 0;
byte[] buffer = new byte[10000];
request.InputStream.Read(buffer, 0, buffer.Length);

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.
10,575 questions
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.
8,974 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,147 questions
{count} votes

2 answers

Sort by: Most helpful
  1. sreejukg 11,006 Reputation points

    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 38,451 Reputation points

    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