Azure Serverless Computing Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it…

  1. Navigate to the Function App listing page. Choose the function app in which you would like to add a new function.
  2. Create a new function by clicking on the + icon as shown in the following screenshot:
  1. If you have created a brand new function, then clicking on the + icon in the preceding step, you would see the Get started quickly with a premade function page. Please click on the create your own custom functions link to navigate to the page where you can see all the built-in templates for creating your Azure Functions. 
  2. In the Choose a template below or go to the quickstart section, choose HTTPTrigger-CSharp as shown in the following screenshot to create a new HTTP trigger function:
  1. Provide a meaningful name. For this example, I have used RegisterUser as the name of the Azure Function.
  2. In the Authorization level drop-down, choose the Anonymous option as shown in the following screenshot. We will learn more about the all the authorization levels in Chapter 9, Implement Best Practices for Azure Functions:
  1. Once you provide the name and choose the Authorization level, click on Create button to create the HTTP trigger function.
  2. As soon as you create the function, all the required code and configuration files will be created automatically and the run.csx file will be opened for you to edit the code. Remove the default code and replace it with the following code:
        using System.Net;
public static async Task<HttpResponseMessage>
Run(HttpRequestMessage req, TraceWriter log)
{
string firstname=null,lastname = null;
dynamic data = await req.Content.ReadAsAsync<object>();
firstname = firstname ?? data?.firstname;
lastname = data?.lastname;
return (lastname + firstname) == null ?
req.CreateResponse(HttpStatusCode.BadRequest,
"Please pass a name on the query string or in the
request body")
:
req.CreateResponse(HttpStatusCode.OK, "Hello " +
firstname + " " + lastname);
}
  1. Save the changes by clicking on the Save button available just above the code editor.
  2. Let's try to test the RegisterUser function using the Test console. Click on the tab named Test as shown in the following screenshot to open the Test console:
  1. Enter the values for firstname and lastname, in the Request body section as shown in the following screenshot:

Please make sure you select POST in the HTTP method drop-down.

  1. Once you have reviewed the input parameters, click on the Run button available at the bottom of the Test console as shown in the following screenshot:
  1. If the input request workload is passed correctly with all the required parameters, you will see a Status 200 OK, and the output in the Output window will be as shown in the preceding screenshot.