Connect functions to Azure Storage using Visual Studio

Azure Functions lets you connect Azure services and other resources to functions without having to write your own integration code. These bindings, which represent both input and output, are declared within the function definition. Data from bindings is provided to the function as parameters. A trigger is a special type of input binding. Although a function has only one trigger, it can have multiple input and output bindings. To learn more, see Azure Functions triggers and bindings concepts.

This article shows you how to use Visual Studio to connect the function you created in the previous quickstart article to Azure Storage. The output binding that you add to this function writes data from the HTTP request to a message in an Azure Queue storage queue.

Most bindings require a stored connection string that Functions uses to access the bound service. To make it easier, you use the Storage account that you created with your function app. The connection to this account is already stored in an app setting named AzureWebJobsStorage.

Prerequisites

Before you start this article, you must:

  • Complete part 1 of the Visual Studio quickstart.
  • Install Azure Storage Explorer. Storage Explorer is a tool that you'll use to examine queue messages generated by your output binding. Storage Explorer is supported on macOS, Windows, and Linux-based operating systems.
  • Sign in to your Azure subscription from Visual Studio.

Download the function app settings

In the previous quickstart article, you created a function app in Azure along with the required Storage account. The connection string for this account is stored securely in app settings in Azure. In this article, you write messages to a Storage queue in the same account. To connect to your Storage account when running the function locally, you must download app settings to the local.settings.json file.

  1. In Solution Explorer, right-click the project and select Publish.

  2. In the Publish tab under Hosting, expand the three dots (...) and select Manage Azure App Service settings.

    Edit the application settings

  3. Under AzureWebJobsStorage, copy the Remote string value to Local, and then select OK.

The storage binding, which uses the AzureWebJobsStorage setting for the connection, can now connect to your Queue storage when running locally.

Register binding extensions

Because you're using a Queue storage output binding, you need the Storage bindings extension installed before you run the project. Except for HTTP and timer triggers, bindings are implemented as extension packages.

  1. From the Tools menu, select NuGet Package Manager > Package Manager Console.

  2. In the console, run the following Install-Package command to install the Storage extensions:

    Install-Package Microsoft.Azure.Functions.Worker.Extensions.Storage.Queues
    

Now, you can add the storage output binding to your project.

Add an output binding

In a C# project, the bindings are defined as binding attributes on the function method. Specific definitions depend on whether your app runs in-process (C# class library) or in an isolated worker process.

Open the HttpExample.cs project file and add the following parameter to the Run method definition:

            [Queue("outqueue"),StorageAccount("AzureWebJobsStorage")] ICollector<string> msg, 

The msg parameter is an ICollector<T> type, representing a collection of messages written to an output binding when the function completes. In this case, the output is a storage queue named outqueue. The StorageAccountAttribute sets the connection string for the storage account. This attribute indicates the setting that contains the storage account connection string and can be applied at the class, method, or parameter level. In this case, you could omit StorageAccountAttribute because you're already using the default storage account.

The Run method definition must now look like the following code:

        [FunctionName("HttpExample")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, 
            [Queue("outqueue"),StorageAccount("AzureWebJobsStorage")] ICollector<string> msg, 
            ILogger log)

Add code that uses the output binding

After the binding is defined, you can use the name of the binding to access it as an attribute in the function signature. By using an output binding, you don't have to use the Azure Storage SDK code for authentication, getting a queue reference, or writing data. The Functions runtime and queue output binding do those tasks for you.

Add code that uses the msg output binding object to create a queue message. Add this code before the method returns.

            if (!string.IsNullOrEmpty(name))
            {
                // Add a message to the output collection.
                msg.Add(name);
            }

At this point, your function must look as follows:

        [FunctionName("HttpExample")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, 
            [Queue("outqueue"),StorageAccount("AzureWebJobsStorage")] ICollector<string> msg, 
            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;

            if (!string.IsNullOrEmpty(name))
            {
                // Add a message to the output collection.
                msg.Add(name);
            }
            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }

Run the function locally

  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.

    Azure local runtime

  3. Paste the URL for the HTTP request into your browser's address bar. Append the query string ?name=<YOUR_NAME> to this URL and run the request. The following image shows the response in the browser to the local GET request returned by the function:

    Function localhost response in the browser

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

A new queue named outqueue is created in your storage account by the Functions runtime when the output binding is first used. You'll use Storage Explorer to verify that the queue was created along with the new message.

Connect Storage Explorer to your account

Skip this section if you've already installed Azure Storage Explorer and connected it to your Azure account.

  1. Run the Azure Storage Explorer tool, select the connect icon on the left, and select Add an account.

    Screenshot of how to add an Azure account to Azure Storage Explorer.

  2. In the Connect dialog, choose Add an Azure account, choose your Azure environment, and then select Sign in....

    Screenshot of the sign-in to your Azure account window.

After you successfully sign in to your account, you see all of the Azure subscriptions associated with your account. Choose your subscription and select Open Explorer.

Examine the output queue

  1. In Storage Explorer, expand the Queues node, and then select the queue named outqueue.

    The queue contains the message that the queue output binding created when you ran the HTTP-triggered function. If you invoked the function with the default name value of Azure, the queue message is Name passed to the function: Azure.

    Screenshot of the queue message shown in Azure Storage Explorer.

  2. Run the function again, send another request, and you see a new message in the queue.

Now, it's time to republish the updated function app to Azure.

Redeploy and verify the updated app

  1. In Solution Explorer, right-click the project and select Publish, then choose Publish to republish the project to Azure.

  2. After deployment completes, you can again use the browser to test the redeployed function. As before, append the query string &name=<yourname> to the URL.

  3. Again view the message in the storage queue to verify that the output binding again generates a new message in the queue.

Clean up resources

Other quickstarts in this collection build upon this quickstart. If you plan to work with subsequent quickstarts, tutorials, or with any of the services you've created in this quickstart, don't clean up the resources.

Resources in Azure refer to function apps, functions, storage accounts, and so forth. They're grouped into resource groups, and you can delete everything in a group by deleting the group.

You've created resources to complete these quickstarts. You might be billed for these resources, depending on your account status and service pricing. If you don't need the resources anymore, here's how to delete them:

  1. In the Azure portal, go to the Resource group page.

    To get to that page from the function app page, select the Overview tab, and then select the link under Resource group.

    Screenshot that shows select the resource group to delete from the function app page.

    To get to that page from the dashboard, select Resource groups, and then select the resource group that you used for this article.

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

  3. Select Delete resource group and follow the instructions.

    Deletion might 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

You've updated your HTTP triggered function to write data to a Storage queue. To learn more about developing Functions, see Develop Azure Functions using Visual Studio.

Next, you should enable Application Insights monitoring for your function app: