Parse X-WWW-Form-URLEncoded data in C#

Had some trouble recently finding resources for parsing X-WWW-Form-URLEncoded data in C# – eventually stackoverflow helped (as usual) but it took a bit more searching than I thought it should. It’s really simple once you realise that urlencoded data in a POST request is parsed the same as a query string in a GET request.

In my case, I was parsing data that came from an Elementor Webhook in an Azure Function App – I’ll do another post on that at some point.

First up, we need to get our data into our application by reading the data POSTed to the application. In my case, it looked like this -basically stolen directly from the Azure Function App webhook trigger template.

C#
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

Once we have the POST request body in a string, it’s pretty easy to get it to a NameValueCollection.

C#
NameValueCollection ourCollection = HttpUtility.ParseQueryString(requestBody);

That’s basically all it is. To get the data out I just did like this:

C#
// Where "fields[email][value]" is the Key of the data I wanted to get
string email = ourCollection["fields[email][value]"];

// and similarly, where "fields[name][value]" is the key of the data I wanted.
string name = ourCollection["fields[name][value]"];

Obviously it might be better to put that data into a class etc but in my case I just needed the values for a quick and dirty fix.

In

Leave a Reply

Your email address will not be published. Required fields are marked *