Parsing WebRequest.Entity (HTTP Post data)

I’m working on a Web Service using the “HandleURL” event. When data is posted to my service, the WebRequest.Entity contains the following:

Content-Disposition: form-data; name="CompanyID"

Content-Disposition: form-data; name="UnixTime"

Content-Disposition: form-data; name="Timezone"

Content-Disposition: form-data; name="DepartmentID"

Content-Disposition: form-data; name="UUID"

Content-Disposition: form-data; name="FirstName"

Content-Disposition: form-data; name="LastName"


Are there any built-in methods for parsing the POST’ed data or do I have to roll-my-own?


You’ll have to make your own. The good news is that the boundary string will be in the headers, so all you’ll need to do is Split on that string to get an array of items, loop over those items and Split each on EndOfLine.Windows to split the header and data portions. RegEx could easily be used to extract the parameter name.

Extracted from a project of mine:

[code]Function MultipartParse(FormData As String, Boundary As String) As Dictionary
Static CRLF As String = EndOfLine.Windows
Dim form As New Dictionary
Dim elements() As String = Split(FormData, “–” + Boundary)’ + CRLF)

Dim ecount As Integer = UBound(elements)
For i As Integer = 1 To ecount
Dim line As String = NthField(elements(i).LTrim, CRLF, 1)
Dim name As String = NthField(line, “;”, 2)
name = NthField(name, “=”, 2)
name = ReplaceAll(name, “”"", “”)
If name.Trim = “” Then Continue For i
Dim j As Integer
Dim nm As String = name
Do Until Not form.HasKey(nm)
j = j + 1
nm = name + Str(j)
If CountFields(line, “;”) < 3 Then 'form field
form.Value(nm) = NthField(elements(i), CRLF + CRLF, 2)
Else 'file field
Dim filename As String = NthField(line, “;”, 3)
filename = NthField(filename, “=”, 2)
filename = ReplaceAll(filename, “”"", “”)
If filename.Trim = “” Then filename = name
Dim tmp As FolderItem = SpecialFolder.Temporary.Child(filename)
Dim bs As BinaryStream = BinaryStream.Create(tmp, True)
Dim filedata As MemoryBlock = elements(i)
Dim t As Integer = InStr(filedata, CRLF + CRLF) + 3
filedata = filedata.StringValue(t, filedata.Size - t - 2)
form.Value(nm) = tmp
End If

Return form

End Function[/code]