2017-03-26 32 views
0

我想用C#构建一个非常简单的Web服务器。我用HttpListener,到目前为止我已经启动并运行。但是当我试图得到InputStream的要求,我总是遇到NullStream,无论我放在GETC#:HttpListener请求InputStream始终是一个空的流

这里是我的代码:

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

,你可以在代码中看到我还试图重启河流的位置,但仍然没有运气。

+0

您的浏览器犯规在实际的InputStream发送任何东西只要打开页面时。所有数据都位于标题中。您可能想编写一个简单的客户端,使用HttpWebRequest类来接收一些数据。 – CSharpie

+0

@CSharpie谢谢你的评论。但我想要的是接收在URL中输入的数据。我不想有一个客户端程序。我也检查了'context.Request.Headers',它没有'samad = 11'数据。 –

+1

'samad = 11'在QueryString中,而不是标头 –

回答

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]); 
+0

我选择了你的答案(实际上是@KevinGosse的答案:D)作为正确的答案。但我也注意到,如果我在'POST'中发送数据,它会转到输入流。我认为把它添加到你的答案是一个好主意(为了完整性),所以有这个问题的其他人可以看到它。 –