Building and Deploying Your First Serverless Azure Function with .NET 8: A Step-by-Step Guide

Leandro Veiga - Sep 24 - - Dev Community

Azure Functions is a powerful serverless compute service from Microsoft Azure, allowing developers to run code without managing the underlying infrastructure. With .NET 8, you can take advantage of the latest features in the .NET ecosystem to build fast and scalable serverless functions.

In this post, we’ll guide you through creating your first Azure Function using .NET 8, then deploying it to Azure.

What Are Azure Functions?

Azure Functions enables you to execute code in response to events without the need to provision or manage servers. It follows a pay-per-execution pricing model, meaning you only pay for the compute resources used when your function runs. Azure Functions supports various languages, including C#, JavaScript, Python, and more.

Some common use cases for Azure Functions include:

  • Running scheduled tasks (e.g., clean-up jobs, sending email notifications)
  • Handling HTTP requests (e.g., APIs)
  • Processing data in real-time from queues, streams, or databases

Step 1: Setting Up the Development Environment

Before you start, make sure you have the following installed:

  • .NET 8 SDK: You can download it from here.
  • Azure Functions Core Tools: These tools allow you to run and test your Azure Functions locally. Install them using the following command:
npm install -g azure-functions-core-tools@4 --unsafe-perm true
Enter fullscreen mode Exit fullscreen mode
  • Azure CLI: The Azure CLI helps with managing resources in Azure. Install it from here.

Once your environment is ready, let's create a new Azure Function project.

Step 2: Creating Your First Azure Function

You can create your first Azure Function with .NET 8 using the Azure Functions Core Tools. Open your terminal or command prompt and run the following command to create a new Azure Functions project:

func init MyFirstFunctionApp --worker-runtime dotnet
Enter fullscreen mode Exit fullscreen mode

This command initializes a new function app in the MyFirstFunctionApp folder using the .NET runtime.

Next, let’s create a simple HTTP-triggered function. Run the following command to add a new function:

func new
Enter fullscreen mode Exit fullscreen mode

Select HTTP trigger when prompted and name the function HelloWorldFunction.

This will create a HelloWorldFunction.cs file containing the code for your function.

Step 3: Writing the Function Code

Open the newly created HelloWorldFunction.cs file in your editor. You’ll see the following default code for the HTTP-triggered function:

using System.IO;
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 System.Threading.Tasks;

public static class HelloWorldFunction
{
    [FunctionName("HelloWorldFunction")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        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;

        return name != null
            ? (ActionResult)new OkObjectResult($"Hello, {name}")
            : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
    }
}
Enter fullscreen mode Exit fullscreen mode

This code defines a simple HTTP-triggered function that responds with a greeting message. It accepts either a GET or POST request, extracts the name from the query string or request body, and returns a message such as "Hello, John!".

Step 4: Running the Function Locally

Before deploying to Azure, it's a good idea to test the function locally. You can do this using the Azure Functions Core Tools. Run the following command to start the function locally:

func start
Enter fullscreen mode Exit fullscreen mode

Once the function starts, you’ll see a local URL for your function:

http://localhost:7071/api/HelloWorldFunction
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to the URL, appending a query string to pass the name parameter:

http://localhost:7071/api/HelloWorldFunction?name=John
Enter fullscreen mode Exit fullscreen mode

You should see the response:

Hello, John
Enter fullscreen mode Exit fullscreen mode

Step 5: Deploying to Azure

Now that your function works locally, it's time to deploy it to Azure. Follow these steps to deploy your function app to Azure:

Step 5.1: Log in to Azure

If you're not logged in to Azure, use the Azure CLI to log in:

az login
Enter fullscreen mode Exit fullscreen mode

Step 5.2: Create a Resource Group

Create a new resource group in Azure for your function app:

az group create --name MyResourceGroup --location "West US"
Enter fullscreen mode Exit fullscreen mode

Step 5.3: Create a Storage Account

Azure Functions requires a storage account to store logs and other data. Create one using the following command:

az storage account create --name mystorageaccount --location "West US" --resource-group MyResourceGroup --sku Standard_LRS
Enter fullscreen mode Exit fullscreen mode

Step 5.4: Create a Function App

Now create the Azure Function App:

az functionapp create --resource-group MyResourceGroup --consumption-plan-location "West US" --runtime dotnet --functions-version 4 --name MyFirstFunctionApp --storage-account mystorageaccount
Enter fullscreen mode Exit fullscreen mode

Step 5.5: Deploy the Function

Finally, deploy the function to Azure using the Azure Functions Core Tools:

func azure functionapp publish MyFirstFunctionApp
Enter fullscreen mode Exit fullscreen mode

Once the deployment is complete, you’ll see the live URL for your function. You can now access it just as you did locally, but using the Azure-hosted URL:

https://<your-function-app-name>.azurewebsites.net/api/HelloWorldFunction?name=John
Enter fullscreen mode Exit fullscreen mode

Step 6: Monitoring Your Function in Azure

Azure provides built-in monitoring for Azure Functions through Application Insights. You can enable Application Insights during the function app creation or add it later via the Azure Portal. Monitoring allows you to track requests, failures, performance, and more.

To enable Application Insights, run:

az monitor app-insights component create --app MyFirstFunctionApp --resource-group MyResourceGroup --location "West US"
Enter fullscreen mode Exit fullscreen mode

Conclusion

Congratulations! You’ve created your first Azure Function using .NET 8 and deployed it to Azure. Azure Functions allows you to build and run serverless applications quickly and easily, handling everything from simple HTTP requests to complex workflows. With .NET 8, you benefit from the latest improvements in performance and developer productivity.

Now that you know the basics, you can explore other triggers such as queues, timers, or blob storage, and expand the power of your Azure Functions.

If you have any questions or need more details, feel free to leave a comment below!

. . . . . . . . . . . . . . . . . .
Terabox Video Player