Search code examples
c#winformshttplistener

C#: HttpListener request InputStream is always an empty stream


I am trying to build a very simple web server with C#. I used HttpListener and so far i got it up and running. But when i try to get InputStream of request, i always encounter NullStream, no matter what i put in GET.

Here is my code:

class WebServer
{
    private HttpListener listener;
    private bool firstRun = true;
    private const string prefixes = "http://127.0.0.1:8080/";

    public void Start()
    {
        if (firstRun)
        {
            listener = new HttpListener();
            listener.Prefixes.Add(prefixes);
            firstRun = false;
        }
        try
        {
            listener.Start();
        }
        catch (HttpListenerException hlex)
        {
            return;
        }
        while (listener.IsListening)
        {
            var context = listener.GetContext();
            context.Request.InputStream.Position = 0;//i even tried to reset stream position 
            var body = new StreamReader(context.Request.InputStream).ReadToEnd();//this is always empty("")

            byte[] b = Encoding.UTF8.GetBytes("ACK");
            context.Response.StatusCode = 200;
            context.Response.KeepAlive = false;
            context.Response.ContentLength64 = b.Length;

            var output = context.Response.OutputStream;
            output.Write(b, 0, b.Length);
            context.Response.Close();
            Console.WriteLine(body);
        }
        listener.Stop();
        listener.Close();
    }

}

To create a GET request i open browser and enter this URL:

http://127.0.0.1:8080/?samad=11

as you can see in the code i also tried to reset stream position to its beginning, but still no luck.


Solution

  • EDIT This answers a question from the comments, not the initial question.

    The information you want is located in the HttpListenerRequest.QueryString

    var context = listener.GetContext();
    var qry = context.Request.QueryString;
    foreach(var key in qry.AllKeys)
        Console.WriteLine("{0} = {1}", key, qry[key]);