【问题标题】:Is there a .NET ready made method to process response body of a HttpListener HttpListenerRequest body?是否有 .NET 现成的方法来处理 HttpListener HttpListenerRequest 主体的响应主体?
【发布时间】:2017-08-16 22:38:58
【问题描述】:

我正在使用 HttpListener 为在 localhost 上以另一种技术编写的应用程序提供 Web 服务器。该应用程序使用简单的表单提交 (application/x-www-form-urlencoded) 向我的软件发出请求。我想知道是否已经编写了一个解析器来将 html 请求文档的正文转换为哈希表或等效项。

考虑到 .NET 似乎已经提供了多少,我很难相信我需要自己编写这个。

提前致谢,

【问题讨论】:

    标签: c# .net http


    【解决方案1】:

    你的意思是像HttpUtility.ParseQueryString 这样给你一个NameValueCollection?这是一些示例代码。您需要更多的错误检查,并且可能使用请求内容类型来确定编码:

    string input = null;
    using (StreamReader reader = new StreamReader (listenerRequest.InputStream)) {
        input = reader.ReadToEnd ();
    }
    NameValueCollection coll = HttpUtility.ParseQueryString (input);
    

    如果您使用的是 HTTP GET 而不是 POST:

    string input = listenerRequest.Url.QueryString;
    NameValueCollection coll = HttpUtility.ParseQueryString (input);
    

    【讨论】:

    • 假设 Jotham 使用 HTTP-GET 而不是 HTTP-POST。不是吗?
    • 我发布的示例实际上是用于 POST。如果你想要 GET... /me 将其添加到示例代码中。
    • 这仍然没有解决他的要求:x-www-form-urlencoded 解析器,而不是查询字符串解析器。
    • @nitzmahone:真的吗?阅读w3.org/TR/html401/interact/forms.html#h-17.13.1。 x-www-form-urlencoded 的 POST 中的数据与等效 GET 的查询字符串相同。
    • 谢谢大家,我的印象是 POST 正文比 GET 查询字符串的相同编码更多。我的错。
    【解决方案2】:

    填写 HttpRequest.Form 的神奇位在 System.Web.HttpRequest 中,但它们不是公开的(反射该类上的“FillInFormCollection”方法以查看)。您必须将管道与 HttpRuntime 集成(基本上是编写一个简单的 ASP.NET 主机)才能充分利用。

    【讨论】:

      【解决方案3】:

      如果您想避免使用HttpUtility.ParseQueryString 所需的对System.Web 的依赖,您可以使用System.Net.Http 中的ParseQueryString 扩展方法ParseQueryString

      确保在您的项目中添加对System.Net.Http 的引用(如果您还没有)。

      请注意,您必须将响应正文转换为有效的 Uri,以便 ParseQueryString(在 System.Net.Http 中)有效。

      string body = "value1=randomvalue1&value2=randomValue2";
      
      // "http://localhost/query?" is added to the string "body" in order to create a valid Uri.
      string urlBody = "http://localhost/query?" + body;
      NameValueCollection coll = new Uri(urlBody).ParseQueryString();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-08
        相关资源
        最近更新 更多