DEV Community

Jacob Smith
Jacob Smith

Posted on

Introduction to Azure Functions Pt. 2 - Creating the Azure Function

Introduction

In this post we will be creating an Azure Function in our HelloAzure.Functions project. We will add an assembly reference to HelloAzure.BusinessLogic in order to add some contrived business logic. Finally we will run the function project locally in order to verify the function works as expected.

Prerequisites

To create the Azure Function we will be using the azure-functions-core-tools cli. Instructions for installing the CLI can be found here. To add an assembly reference from our BusinessLogic assembly we'll use the dotnet cli which is included in the .NET Core SDK. We will be using version 2.1 of the SDK. The SDK installer can be found here.

We will be using the command line in this section. Some basic knowledge of the command line will be useful.

Shell commands will be prefixed with $.

This wiki assumes that you have created a repository in a source control provider such as GitHub and that you have cloned that repository locally.

Creating the Azure Function

  1. Change directories into the Functions project of your locally cloned repository.

    $ cd ~/code/HelloAzure/HelloAzure.Functions/
    
  2. Create a new Azure Function in the project.

    $ func new
    
    1. This will start the function creation wizard.
    2. When prompted for a trigger select Http Trigger.
    3. Name the function SayHello.
    4. You should see the following output

      The function "SayHello" was created successfully from the "HttpTrigger" template.
      
  3. Your HelloAzure.Functions/ directory should now have a SayHello.cs file in it.

    .
    +-- HelloAzure.Functions/
    |   +-- SayHello.cs
    |   +-- ...
    

Adding a reference to our BusinessLogic assembly

  1. From your HelloAzure.Functions/ directory add a reference to the BusinessLogic assembly.

    $ dotnet add reference ../HelloAzure.BusinessLogic/HelloAzure.BusinessLogic.csproj
    
    1. This command will add a project reference to your HelloAzure_Functions.csproj file that points to the HelloAzure.BusinessLogic project.

Add "business logic" to the function

  1. In a text editor modify the contents of SayHello.cs

    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    using HelloAzure.BusinessLogic;
    
    namespace HelloAzure.Functions
    {
        public static class SayHello
        {
            [FunctionName("SayHello")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
            {
                GreetingService greetingService = new GreetingService();
                log.LogInformation("C# HTTP trigger function processed a request.");
    
                string name = req.Query["name"];
    
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                name = name ?? data?.name;
    
                if (name != null) {
                    string greeting = greetingService.GetGreeting(name);
                    return (ActionResult)new OkObjectResult(greeting);
                }
    
                return new BadRequestObjectResult("Please pass a name on the query string or in the request body");
            }
        }
    }
    
    1. In our changes we added a using statement for HelloAzure.BusinessLogic.
    2. Next we instantiated an instance of the GreetingService.
    3. Finally we modified the return logic to generate a greeting using our GreetingService instead of using a hard-coded string.

Running the function locally

  1. From your HelloAzure.Functions/ directory start the function project.

    $ func start --build
    
    1. This will build the functions project and start it.
    2. The --build flag is needed since this is a .NET Core functions project and it must be built.
    3. This will start an HTTP Server and point your functions to it.
    4. You should see output containing the following.

      Http Functions:
      
      SayHello: [GET,POST] http://localhost:7071/api/SayHello
      
  2. If you visit the URL above in a browser and add a query string parameter for name you should see a response with the message Hello, <name>. If you do then congrats! Your function is working.

Recap

In this post we added an Azure Function to our HelloAzure.Functions project. We added a reference to our HelloAzure.BusinessLogic class library in order to add some contrived business logic to illustrate how you might add logic to a function. Finally we ran our function project locally in order to verify the function works.

This would be a good time to commit the changes you've made to source.

The next step is creating Azure Function resources.

Top comments (0)