5-Minute-Snack: Understanding TWebRequest’s ContentFields and QueryFields with regard to MethodType
It seems rather obvious, but somehow the two are always being mixed up.
Thus, this will be 5 minutes well spent if you ever will implement a REST Web Service using TWebRequest .
Considering the documentation QueryFields refer to parameters in the URL and ContentFields refers to the content of a POST request message. Of course, both GET and POST requests can have QueryFields . However, GET requests do not have ContentFields . Both parameters are mapped to TStringList in Delphi. Multiple values can be separated with an ampersand (& ).
This seems all to be pretty straight forward. Let’s see how it works in reality.
I wrote an example POST request that has the following implementation:
procedure TModMain.WebModule1webSetResultsAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); begin Response.Content := '<html>' + '<body>' + 'QueryFields: ' + Request.QueryFields.Text + '<br/>' + 'ContentFields: ' + Request.ContentFields.Text + '</body>' + '</html>'; Handled := True; end;
As expected when sending the following POST request to the URL
with the content
set up in the Fiddler composer…
…yields the following result:
<html> <body> QueryFields: skip=0<br/> ContentFields: Name=Holger </body> </html>
Delphi gives us very easy access to parameters in URLs and the content of a POST request this way. The TWebRequest class also makes it possible to determine the method type of the request easily using TWebRequest.MethodType .
One might ask why that is necessary to check inside the method as the TWebActionItem also has a MethodType and thus the event is only called for one method type. Well, there is a special method type.
The type is defined as follows:
TMethodType = (mtAny, mtGet, mtPut, mtPost, mtHead, mtDelete, mtPatch);
You might implement one action event handler for all the different method types in Delphi and use mtAny. Inside the event handler you will then determine the method type using the MethodType property of the request.
One thing is very important to note: Accessing ContentFields will not throw an exception or the property will not be nil either; instead the list will simply not contain any elements.