是否有.NET就绪方法来处理HttpListener HttpListenerRequest主体的响应主体?

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

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

提前致谢,

你的意思是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); 

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

如果要避免使用HttpUtility.ParseQueryString所需的System.Web依赖,可以使用System.Net.HttpUri扩展方法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();