Jotham Jotham -3 years ago 153
C# Question

Is there a .NET ready made method to process response body of a HttpListener HttpListenerRequest body?

I'm using HttpListener to provide a web server to an application written in another technology on localhost. The application is using a simple form submission (application/x-www-form-urlencoded) to make its requests to my software. I want to know if there is already a parser written to convert the body of the html request document into a hash table or equivalent.

I find it hard to believe I need to write this myself, given how much .NET already seems to provide.

Thanks in advance,

Answer Source

You mean something like HttpUtility.ParseQueryString that gives you a NameValueCollection? Here's some sample code. You need more error checking and maybe use the request content type to figure out the encoding:

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

If you're using HTTP GET instead of POST:

string input = listenerRequest.Url.QueryString;
NameValueCollection coll = HttpUtility.ParseQueryString (input);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download