Parse POST parameters from HttpListener

Den Kison picture Den Kison · Sep 26, 2013 · Viewed 19k times · Source

Let's say i have HttpListener. It listen some port and ip. When i send POST request it catch it. How can i parse POST parameters from HttpListenerRequest?

HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;

if ( request.HttpMethod == "POST" )
{
  // Here i can read all parameters in string but how to parse each one i don't know                                            
}

Answer

Mouseroot picture Mouseroot · Apr 24, 2014

I ran into this issue a few hours ago and banged out this answer hoping it helps someone when parsing out POST data

//using System.Web and Add a Reference to System.Web
Dictionary<string, string> postParams = new Dictionary<string, string>();
string[] rawParams = rawData.Split('&');
foreach (string param in rawParams)
{
    string[] kvPair = param.Split('=');
    string key = kvPair[0];
    string value = HttpUtility.UrlDecode(kvPair[1]);
    postParams.Add(key, value);
}

//Usage
Console.WriteLine("Hello " + postParams["username"]);