Develop and publish .NET 5 functions using Azure Functions

This article shows you how to work with C# functions using .NET 5.0, which run out-of-process from the Azure Functions runtime. You'll learn how to create, debug locally, and publish these .NET isolated process functions to Azure. In Azure, these functions run in an isolated process that supports .NET 5.0. To learn more, see Guide for running functions on .NET 5.0 in Azure.

If you don't need to support .NET 5.0 or run your functions out-of-process, you might want to instead create a C# class library function.

Prerequisites

  • Visual Studio 2019 version 16.10 or later. Your install must include either the Azure development or the ASP.NET and web development workload.

Create a local function project

In Azure Functions, a function project is a container for one or more individual functions that each responds to a specific trigger. All functions in a project share the same local and hosting configurations. In this section, you create a function project that contains a single function.

  1. Choose the Azure icon in the Activity bar, then in the Azure: Functions area, select the Create new project... icon.

    Choose Create a new project

  2. Choose a directory location for your project workspace and choose Select.

    Note

    These steps were designed to be completed outside of a workspace. In this case, do not select a project folder that is part of a workspace.

  3. Provide the following information at the prompts:

    • Select a language for your function project: Choose C#.

    • Select a .NET runtime: Choose .NET 5 isolated.

    • Select a template for your project's first function: Choose HTTP trigger.

    • Provide a function name: Type HttpExample.

    • Provide a namespace: Type My.Functions.

    • Authorization level: Choose Anonymous, which enables anyone to call your function endpoint. To learn about authorization level, see Authorization keys.

    • Select how you would like to open your project: Choose Add to workspace.

  4. Using this information, Visual Studio Code generates an Azure Functions project with an HTTP trigger. You can view the local project files in the Explorer. To learn more about files that are created, see Generated project files.

  1. Run the func init command, as follows, to create a functions project in a folder named LocalFunctionProj:

    func init LocalFunctionProj --worker-runtime dotnetisolated
    

    Specifying dotnetisolated creates a project that runs on .NET 5.0.

  2. Navigate into the project folder:

    cd LocalFunctionProj
    

    This folder contains various files for the project, including the local.settings.json and host.json configurations files. Because local.settings.json can contain secrets downloaded from Azure, the file is excluded from source control by default in the .gitignore file.

  3. Add a function to your project by using the following command, where the --name argument is the unique name of your function (HttpExample) and the --template argument specifies the function's trigger (HTTP).

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

    func new creates an HttpExample.cs code file.

  1. From the Visual Studio menu, select File > New > Project.

  2. In Create a new project, enter functions in the search box, choose the Azure Functions template, and then select Next.

  3. In Configure your new project, enter a Project name for your project, and then select Create. The function app name must be valid as a C# namespace, so don't use underscores, hyphens, or any other nonalphanumeric characters.

  4. For the Create a new Azure Functions application settings, use the values in the following table:

    Setting Value Description
    .NET version .NET 5 (Isolated) This value creates a function project that runs on .NET 5.0 in an isolated process.
    Function template HTTP trigger This value creates a function triggered by an HTTP request.
    Storage account (AzureWebJobsStorage) Storage emulator Because a function app in Azure requires a storage account, one is assigned or created when you publish your project to Azure. An HTTP trigger doesn't use an Azure Storage account connection string; all other trigger types require a valid Azure Storage account connection string.
    Authorization level Anonymous The created function can be triggered by any client without providing a key. This authorization setting makes it easy to test your new function. For more information about keys and authorization, see Authorization keys and HTTP and webhook bindings.

    Azure Functions project settings

    Make sure you set the Authorization level to Anonymous. If you choose the default level of Function, you're required to present the function key in requests to access your function endpoint.

  5. Select Create to create the function project and HTTP trigger function.

Visual Studio creates a project and class that contains boilerplate code for the HTTP trigger function type. The boilerplate code sends a "Welcome to Azure Functions!" HTTP response. The HttpTrigger attribute specifies that the function is triggered by an HTTP request.

Rename the function

The FunctionName method attribute sets the name of the function, which by default is generated as Function1. Since the tooling doesn't let you override the default function name when you create your project, take a minute to create a better name for the function class, file, and metadata.

  1. In File Explorer, right-click the Function1.cs file and rename it to HttpExample.cs.

  2. In the code, rename the Function1 class to HttpExample.

  3. In the HttpTrigger method named Run, rename the FunctionName method attribute to HttpExample and the value passed to the GetLogger method.

Your function definition should now look like the following code:

public static class HttpExample
{
    [Function("HttpExample")]
    public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
        FunctionContext executionContext)
    {
        var logger = executionContext.GetLogger("HttpExample");

Now that you've renamed the function, you can test it on your local computer.

Run the function locally

Visual Studio integrates with Azure Functions Core Tools so that you can test your functions locally using the full Azure Functions runtime.

  1. To run your function, press F5 in Visual Studio. You might need to enable a firewall exception so that the tools can handle HTTP requests. Authorization levels are never enforced when you run a function locally.

  2. Copy the URL of your function from the Azure Functions runtime output and run the request. A welcome to Functions message is displayed when the function runs successfully and logs are written to the runtime output.

  3. To stop debugging, press Shift+F5 in Visual Studio.

After you've verified that the function runs correctly on your local computer, it's time to publish the project to Azure.

Run the function locally

Visual Studio Code integrates with Azure Functions Core tools to let you run this project on your local development computer before you publish to Azure.

  1. To call your function, press F5 to start the function app project. Output from Core Tools is displayed in the Terminal panel. Your app starts in the Terminal panel. You can see the URL endpoint of your HTTP-triggered function running locally.

    Local function VS Code output

    If you have trouble running on Windows, make sure that the default terminal for Visual Studio Code isn't set to WSL Bash.

  2. With Core Tools running, go to the Azure: Functions area. Under Functions, expand Local Project > Functions. Right-click (Windows) or Ctrl - click (macOS) the HttpExample function and choose Execute Function Now....

    Execute function now from Visual Studio Code

  3. In Enter request body you see the request message body value of { "name": "Azure" }. Press Enter to send this request message to your function.

    You could have instead sent an HTTP GET request to the http://localhost:7071/api/HttpExample address in a web browser.

  4. When the function executes locally and returns a response, a notification is raised in Visual Studio Code. Information about the function execution is shown in Terminal panel.

  5. Press Ctrl + C to stop Core Tools and disconnect the debugger.

Run the function locally

  1. Run your function by starting the local Azure Functions runtime host from the LocalFunctionProj folder:

    func start
    

    Toward the end of the output, the following lines should appear:

     ...
    
     Now listening on: http://0.0.0.0:7071
     Application started. Press Ctrl+C to shut down.
    
     Http Functions:
    
             HttpExample: [GET,POST] http://localhost:7071/api/HttpExample
     ...
    
     

    Note

    If HttpExample doesn't appear as shown above, you likely started the host from outside the root folder of the project. In that case, use Ctrl+C to stop the host, navigate to the project's root folder, and run the previous command again.

  2. Copy the URL of your HttpExample function from this output to a browser and append the query string ?name=<YOUR_NAME>, making the full URL like http://localhost:7071/api/HttpExample?name=Functions. The browser should display a response message that echoes back your query string value. The terminal in which you started your project also shows log output as you make requests.

  3. When you're done, use Ctrl+C and choose y to stop the functions host.

Create supporting Azure resources for your function

Before you can deploy your function code to Azure, you need to create three resources:

  • A resource group, which is a logical container for related resources.
  • A Storage account, which is used to maintain state and other information about your functions.
  • A function app, which provides the environment for executing your function code. A function app maps to your local function project and lets you group functions as a logical unit for easier management, deployment, and sharing of resources.

Use the following commands to create these items.

  1. If you haven't done so already, sign in to Azure:

    az login
    

    The az login command signs you into your Azure account.

  2. Create a resource group named AzureFunctionsQuickstart-rg in the westeurope region:

    az group create --name AzureFunctionsQuickstart-rg --location westeurope
    

    The az group create command creates a resource group. You generally create your resource group and resources in a region near you, using an available region returned from the az account list-locations command.

  3. Create a general-purpose storage account in your resource group and region:

    az storage account create --name <STORAGE_NAME> --location westeurope --resource-group AzureFunctionsQuickstart-rg --sku Standard_LRS
    

    The az storage account create command creates the storage account.

    In the previous example, replace <STORAGE_NAME> with a name that is appropriate to you and unique in Azure Storage. Names must contain three to 24 characters numbers and lowercase letters only. Standard_LRS specifies a general-purpose account, which is supported by Functions.

  4. Create the function app in Azure:

    az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location westeurope --runtime dotnet-isolated --runtime-version 5.0 --functions-version 3 --name <APP_NAME> --storage-account <STORAGE_NAME>
    

    The az functionapp create command creates the function app in Azure.

    In the previous example, replace <STORAGE_NAME> with the name of the account you used in the previous step, and replace <APP_NAME> with a globally unique name appropriate to you. The <APP_NAME> is also the default DNS domain for the function app.

    This command creates a function app running .NET 5.0 under the Azure Functions Consumption Plan. This plan should be free for the amount of usage you incur in this article. The command also provisions an associated Azure Application Insights instance in the same resource group. Use this instance to monitor your function app and view logs. For more information, see Monitor Azure Functions. The instance incurs no costs until you activate it.

Deploy the function project to Azure

After you've successfully created your function app in Azure, you're now ready to deploy your local functions project by using the func azure functionapp publish command.

In the following example, replace <APP_NAME> with the name of your app.

func azure functionapp publish <APP_NAME>

The publish command shows results similar to the following output (truncated for simplicity):

...

Getting site publishing info...
Creating archive for current directory...
Performing remote build for functions project.

...

Deployment successful.
Remote build succeeded!
Syncing triggers...
Functions in msdocs-azurefunctions-qs:
    HttpExample - [httpTrigger]
        Invoke url: https://msdocs-azurefunctions-qs.azurewebsites.net/api/httpexample

Publish the project to Azure

Before you can publish your project, you must have a function app in your Azure subscription. Visual Studio publishing creates a function app for you the first time you publish your project.

  1. In Solution Explorer, right-click the project and select Publish and in Target, select Azure then Next.

  2. For the Specific target, choose Azure Function App (Windows), which creates a function app that runs on Windows.

  3. In Function Instance, choose Create a new Azure Function...

    Create a new function app instance

  4. Create a new instance using the values specified in the following table:

    Setting Value Description
    Name Globally unique name Name that uniquely identifies your new function app. Accept this name or enter a new name. Valid characters are: a-z, 0-9, and -.
    Subscription Your subscription The Azure subscription to use. Accept this subscription or select a new one from the drop-down list.
    Resource group Name of your resource group The resource group in which to create your function app. Select an existing resource group from the drop-down list or choose New to create a new resource group.
    Plan Type Consumption When you publish your project to a function app that runs in a Consumption plan, you pay only for executions of your functions app. Other hosting plans incur higher costs.
    Location Location of the app service Choose a Location in a region near you or other services your functions access.
    Azure Storage General-purpose storage account An Azure Storage account is required by the Functions runtime. Select New to configure a general-purpose storage account. You can also choose an existing account that meets the storage account requirements.

    Create App Service dialog

  5. Select Create to create a function app and its related resources in Azure. Status of resource creation is shown in the lower left of the window.

  6. Back in Functions instance, make sure that Run from package file is checked. Your function app is deployed using Zip Deploy with Run-From-Package mode enabled. This is the recommended deployment method for your functions project, since it results in better performance.

    Finish profile creation

  7. Select Finish, and on the Publish page, select Publish to deploy the package containing your project files to your new function app in Azure.

    After the deployment completes the root URL of the function app in Azure is shown in the Publish tab.

  8. In the Publish tab, choose Manage in Cloud Explorer. This opens the new function app Azure resource in Cloud Explorer.

    Publish success message

    Cloud Explorer lets you use Visual Studio to view the contents of the site, start and stop the function app, and browse directly to function app resources on Azure and in the Azure portal.

Verify your function in Azure

  1. In Cloud Explorer, your new function app should be selected. If not, expand your subscription > App Services, and select your new function app.

  2. Right-click the function app and choose Open in Browser. This opens the root of your function app in your default web browser and displays the page that indicates your function app is running.

    Function app running

  3. In the address bar in the browser, append the path /api/HttpExample to the base URL and run the request.

  4. Go to this URL and you see the same response in the browser you had when running locally.

Sign in to Azure

Before you can publish your app, you must sign in to Azure.

  1. If you aren't already signed in, choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose Sign in to Azure.... If you don't already have one, you can Create a free Azure account. Students can create a free Azure account for Students.

    Sign in to Azure within VS Code

    If you're already signed in, go to the next section.

  2. When prompted in the browser, choose your Azure account and sign in using your Azure account credentials.

  3. After you've successfully signed in, you can close the new browser window. The subscriptions that belong to your Azure account are displayed in the Side bar.

Publish the project to Azure

In this section, you create a function app and related resources in your Azure subscription and then deploy your code.

Important

Publishing to an existing function app overwrites the content of that app in Azure.

  1. Choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose the Deploy to function app... button.

    Publish your project to Azure

  2. Provide the following information at the prompts:

    • Select folder: Choose a folder from your workspace or browse to one that contains your function app. You won't see this prompt when you already have a valid function app opened.

    • Select subscription: Choose the subscription to use. You won't see this prompt when you only have one subscription.

    • Select Function App in Azure: Choose - Create new Function App. (Don't choose the Advanced option, which isn't covered in this article.)

    • Enter a globally unique name for the function app: Type a name that is valid in a URL path. The name you type is validated to make sure that it's unique in Azure Functions.

    • Select a runtime stack: Choose .NET 5 (non-LTS).

    • Select a location for new resources: For better performance, choose a region near you.

    In the notification area, you see the status of individual resources as they're created in Azure.

    Notification of Azure resource creation

  3. When completed, the following Azure resources are created in your subscription, using names based on your function app name:

    • A resource group, which is a logical container for related resources.
    • A standard Azure Storage account, which maintains state and other information about your projects.
    • A consumption plan, which defines the underlying host for your serverless function app.
    • A function app, which provides the environment for executing your function code. A function app lets you group functions as a logical unit for easier management, deployment, and sharing of resources within the same hosting plan.
    • An Application Insights instance connected to the function app, which tracks usage of your serverless function.

    A notification is displayed after your function app is created and the deployment package is applied.

    Tip

    By default, the Azure resources required by your function app are created based on the function app name you provide. By default, they are also created in the same new resource group with the function app. If you want to either customize the names of these resources or reuse existing resources, you need to instead publish the project with advanced create options.

  4. Select View Output in this notification to view the creation and deployment results, including the Azure resources that you created. If you miss the notification, select the bell icon in the lower right corner to see it again.

    Create complete notification

Invoke the function on Azure

Because your function uses an HTTP trigger, you invoke it by making an HTTP request to its URL in the browser or with a tool like curl.

Copy the complete Invoke URL shown in the output of the publish command into a browser address bar, appending the query parameter &name=Functions. The browser should display similar output as when you ran the function locally.

The output of the function run on Azure in a browser

Run the function in Azure

  1. Back in the Azure: Functions area in the side bar, expand your subscription, your new function app, and Functions. Right-click (Windows) or Ctrl - click (macOS) the HttpExample function and choose Execute Function Now....

    Execute function now in Azure from Visual Studio Code

  2. In Enter request body you see the request message body value of { "name": "Azure" }. Press Enter to send this request message to your function.

  3. When the function executes in Azure and returns a response, a notification is raised in Visual Studio Code.

Clean up resources

You created resources to complete this article. You may be billed for these resources, depending on your account status and service pricing.

Use the following command to delete the resource group and all its contained resources to avoid incurring further costs.

az group delete --name AzureFunctionsQuickstart-rg

Use the following steps to delete the function app and its related resources to avoid incurring any further costs.

  1. In Visual Studio Code, press F1 to open the command palette. In the command palette, search for and select Azure Functions: Open in portal.

  2. Choose your function app, and press Enter. The function app page opens in the Azure portal.

  3. In the Overview tab, select the named link next to Resource group.

    Select the resource group to delete from the function app page.

  4. In the Resource group page, review the list of included resources, and verify that they are the ones you want to delete.

  5. Select Delete resource group, and follow the instructions.

    Deletion may take a couple of minutes. When it's done, a notification appears for a few seconds. You can also select the bell icon at the top of the page to view the notification.

Use the following steps to delete the function app and its related resources to avoid incurring any further costs.

  1. In the Cloud Explorer, expand your subscription > App Services, right-click your function app, and choose Open in Portal.

  2. In the function app page, select the Overview tab and then select the link under Resource group.

    Select the resource group to delete from the function app page

  3. In the Resource group page, review the list of included resources, and verify that they're the ones you want to delete.

  4. Select Delete resource group, and follow the instructions.

    Deletion may take a couple of minutes. When it's done, a notification appears for a few seconds. You can also select the bell icon at the top of the page to view the notification.

Next steps