Create Your First Azure Function with C#

This guide will walk you through the process of creating and running your very first Azure Function using C#. Azure Functions is a serverless compute service that enables you to run code on-demand without explicitly provisioning or managing infrastructure.

By the end of this tutorial, you will have a basic HTTP-triggered function that you can test locally.

Prerequisites

  • .NET SDK: Ensure you have the latest .NET SDK installed. You can download it from the official .NET website.
  • Azure Functions Core Tools: Install the Azure Functions Core Tools for local development and debugging.
  • npm install -g azure-functions-core-tools@4 --unsafe-perm true
  • Code Editor: A code editor like Visual Studio Code, Visual Studio, or JetBrains Rider.

Setting Up Your Environment

First, let's create a new Azure Functions project. Open your terminal or command prompt, navigate to the directory where you want to create your project, and run the following commands:

func init MyFirstFunctionApp --worker-runtime dotnet --language csharp
cd MyFirstFunctionApp

This command initializes a new function app project named MyFirstFunctionApp using the .NET runtime and C# language.

Creating Your First Function

Now, let's add an HTTP-triggered function to your project. Run the following command in your terminal:

func new --name HttpTriggerCSharp --template "HTTP trigger" --authlevel "anonymous"

This command creates a new function named HttpTriggerCSharp of type "HTTP trigger" with anonymous authentication. This will generate a few files for your new function, including HttpTriggerCSharp.cs and HttpTriggerCSharp.csproj.

Code Example

HTTP Trigger

Open the HttpTriggerCSharp.cs file. You'll see code similar to this:

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; namespace MyFirstFunctionApp { public static class HttpTriggerCSharp { [FunctionName("HttpTriggerCSharp")] public static async Task Run( [HttpTrigger(AuthorizationLevel.Anonymous, "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; string responseMessage = string.IsNullOrEmpty(name) ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response." : $"Hello, {name}! This HTTP triggered function executed successfully."; return new OkObjectResult(responseMessage); } } }

This function:

  • Is triggered by HTTP requests (GET or POST).
  • Looks for a name parameter in the query string or request body.
  • Returns a personalized greeting or a default message.

Timer Trigger (Optional)

To add a Timer Trigger, navigate to your project directory and run:

func new --name TimerTriggerCSharp --template "Timer trigger"

This will create a TimerTriggerCSharp.cs file with a predefined timer function. You can configure the schedule in the function.json file for this trigger.

Testing Your Function

To test your function locally, navigate to your project's root directory in the terminal and run:

func start

The Azure Functions Core Tools will start a local runtime. You should see output indicating your HTTP-triggered function is running and will provide a local URL, usually something like http://localhost:7071/api/HttpTriggerCSharp.

You can test this URL using your web browser or tools like cURL or Postman:

  • Browser (GET request): Open http://localhost:7071/api/HttpTriggerCSharp?name=World. You should see "Hello, World! This HTTP triggered function executed successfully."
  • cURL (POST request):
    curl -X POST -H "Content-Type: application/json" -d '{"name": "AzureUser"}' http://localhost:7071/api/HttpTriggerCSharp
    You should see "Hello, AzureUser! This HTTP triggered function executed successfully."

Deployment

Once you're satisfied with your function, you can deploy it to Azure. This typically involves using the Azure CLI or VS Code extensions. The deployment process will vary based on your Azure setup.

For more details on deployment, refer to the official Azure Functions deployment documentation.

Next Steps

Congratulations on creating your first Azure Function! Here are some ideas for what to explore next:

  • Other Trigger Types: Explore Blob Triggers, Queue Triggers, and more.
  • Bindings: Learn how to use input and output bindings to interact with other Azure services like Cosmos DB, Storage Queues, and Service Bus.
  • Error Handling and Logging: Implement robust error handling and advanced logging strategies.
  • Development Patterns: Understand durable functions for building stateful workflows.