C#:HttpListener请求InputStream始终是一个空流

时间:2017-03-26 08:10:08

标签: c# winforms httplistener

我正在尝试使用C#构建一个非常简单的Web服务器。我使用了HttpListener,到目前为止我已经开始运行了。但是,当我尝试获取InputStream请求时,无论我放入NullStream,我总会遇到GET

这是我的代码:

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

}

要创建GET请求,请打开浏览器并输入以下网址:

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

正如你在代码中看到的那样,我也尝试将流位置重置为它的开头,但仍然没有运气。

1 个答案:

答案 0 :(得分:1)

您想要的信息位于HttpListenerRequest.QueryString

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