Previous Tutorial: Azure Functions – Part 2: Serving HTML Pages with Azure Functions
Serving static pages is interesting, but a real application needs input from the user, and in the web this is mostly done by sending a query strings in an HTTP GET request, or by posting data in an HTTP POST request. Let’s see how we can handle this in Azure Functions.
So let’s go to our function app and create a new function:
As before, this function will have an HTTP trigger:
And lastly let’s set the language to C#, name it “HandlingGetAndPost”, and set the authentication to Anonymous:
Once again we get the default Azure HTTP Function template for C#, which in this case also contains much code that is relevant to this example! The default examples uses
to fetch the first parameter called “name” that comes in the query string.
req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
We will add some more code so the function can handle both GET and POST requests, and depending on the type of request it receives, parse the query string or the payload send in the POST request:
req.Method we check if the request was done with the GET or POST verb, and based on that we process the query string or the body of the request to fetch the value for “name”. Pretty straightforward.
So let’s test this through the Azure portal. On the right side of the editor there is a “Test” tab where we can set the query parameters and the request body, select which HTTP method to use, and send the data to the service by clicking on “Run” on the lower right corner.
Works like a charm 👍