使用 Visual Studio 将函数连接到 Azure 存储Connect functions to Azure Storage using Visual Studio

无需编写自己的集成代码,即可使用 Azure Functions 将 Azure 服务和其他资源连接到函数。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. 有关详细信息,请参阅 Azure Functions 触发器和绑定的概念To learn more, see Azure Functions triggers and bindings concepts.

本文介绍如何使用 Visual Studio 将在前一篇快速入门文章中创建的函数连接到 Azure 存储。This article shows you how to use Visual Studio to connect the function you created in the previous quickstart article to Azure Storage. 添加到此函数的输出绑定会将 HTTP 请求中的数据写入到 Azure 队列存储队列中的消息。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. 与此帐户建立的连接已存储在名为 AzureWebJobsStorage 的应用设置中。The connection to this account is already stored in an app setting named AzureWebJobsStorage.

先决条件Prerequisites

在开始学习本文之前,必须:Before you start this article, you must:

下载函数应用设置Download the function app settings

前一篇快速入门文章中,你已在 Azure 中创建了一个函数应用,并创建了所需的存储帐户。In the previous quickstart article, you created a function app in Azure along with the required Storage account. 此帐户的连接字符串安全存储在 Azure 中的应用设置内。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. 若要在本地运行函数时连接到该存储帐户,必须将应用设置下载到 local.settings.json 文件。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. 在“操作”下,选择“编辑 Azure 应用服务设置”。 Under Actions, select Edit Azure App Service Settings.

    编辑应用程序设置

  3. 在“AzureWebJobsStorage”下,将“Remote”字符串值复制到“Local”,然后选择“确定”。 Under AzureWebJobsStorage, copy the Remote string value to Local, and then select OK.

现在,使用 AzureWebJobsStorage 设置建立连接的存储绑定可以在本地运行时连接到队列存储。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. 绑定(HTTP 和计时器触发器除外)将实现为扩展包。Except for HTTP and timer triggers, bindings are implemented as extension packages.

  1. 在“工具”菜单中,选择“NuGet 包管理器” > “包管理器控制台”。 From the Tools menu, select NuGet Package Manager > Package Manager Console.

  2. 在控制台中,运行以下 Install-Package 命令安装存储扩展:In the console, run the following Install-Package command to install the Storage extensions:

    Install-Package Microsoft.Azure.WebJobs.Extensions.Storage -Version 3.0.6
    

现在,你可以将存储输出绑定添加到项目。Now, you can add the storage output binding to your project.

添加输出绑定Add an output binding

在 C# 类库项目中,绑定被定义为函数方法上的绑定属性。In a C# class library project, the bindings are defined as binding attributes on the function method. 然后,基于这些属性自动生成 Functions 所需的 function.json 文件。The function.json file required by Functions is then auto-generated based on these attributes.

打开 HttpExample.cs 项目文件,并将以下参数添加到 Run 方法定义中:Open the HttpExample.cs project file and add the following parameter to the Run method definition:

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

msg 参数为 ICollector<T> 类型,表示函数完成时写入输出绑定的消息集合。The msg parameter is an ICollector<T> type, which represents a collection of messages that are written to an output binding when the function completes. 在这种情况下,输出是名为的 outqueue 存储队列。In this case, the output is a storage queue named outqueue. 存储帐户的连接字符串由 StorageAccountAttribute 设置。The connection string for the Storage account is set by the StorageAccountAttribute. 此属性指示包含存储帐户连接字符串的设置,可以在类、方法或参数级别应用。This attribute indicates the setting that contains the Storage account connection string and can be applied at the class, method, or parameter level. 在这种情况下,可以省略 StorageAccountAttribute,因为你已使用默认存储帐户。In this case, you could omit StorageAccountAttribute because you are already using the default storage account.

Run 方法定义如下所示:The Run method definition should now look like the following:

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

添加使用输出绑定的代码Add code that uses the output binding

定义绑定后,可以使用绑定的 name,将其作为函数签名中的属性进行访问。After the binding is defined, you can use the name of the binding to access it as an attribute in the function signature. 使用输出绑定时,无需使用 Azure 存储 SDK 代码进行身份验证、获取队列引用或写入数据。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. Functions 运行时和队列输出绑定将为你执行这些任务。The Functions runtime and queue output binding do those tasks for you.

添加使用 msg 输出绑定对象来创建队列消息的代码。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(string.Format("Name passed to the function: {0}", name));
}

此时,你的函数应如下所示:At this point, your function should look as follows:

[FunctionName("HttpExample")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "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(string.Format("Name passed to the function: {0}", 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. 若要运行函数,请在 Visual Studio 中按 F5。To run your function, press F5 in Visual Studio. 你可能需要启用防火墙例外,这样工具才能处理 HTTP 请求。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. 从 Azure Functions 运行时输出复制函数的 URL。Copy the URL of your function from the Azure Functions runtime output.

    Azure 本地运行时

  3. 将 HTTP 请求的 URL 粘贴到浏览器的地址栏中。Paste the URL for the HTTP request into your browser's address bar. 将查询字符串 ?name=<YOUR_NAME> 追加到此 URL 并运行请求。Append the query string ?name=<YOUR_NAME> to this URL and run the request. 下图显示了浏览器中函数返回的对本地 GET 请求的响应。The following image shows the response in the browser to the local GET request returned by the function:

    浏览器中的函数 localhost 响应

  4. 若要停止调试,请在 Visual Studio 中按 Shift+F5。To stop debugging, press Shift+F5 in Visual Studio.

首次使用输出绑定时,Functions 运行时会在存储帐户中创建名为 outqueue 的新队列。A new queue named outqueue is created in your storage account by the Functions runtime when the output binding is first used. 你将使用 Cloud Explorer 来验证队列是否与新消息一起创建。You'll use Cloud Explorer to verify that the queue was created along with the new message.

检查输出队列Examine the output queue

  1. 在 Visual Studio 的“视图”菜单中,选择“Cloud Explorer”。 In Visual Studio from the View menu, select Cloud Explorer.

  2. 在“Cloud Explorer”中,展开你的 Azure 订阅和“存储帐户”,然后展开函数使用的存储帐户。 In Cloud Explorer, expand your Azure subscription and Storage Accounts, then expand the storage account used by your function. 如果你忘记了存储帐户名称,请查看 local.settings.json 文件中的 AzureWebJobsStorage 连接字符串设置。If you can't remember the storage account name, check the AzureWebJobsStorage connection string setting in the local.settings.json file.

  3. 展开“队列”节点,然后双击名为 outqueue 的队列,在 Visual Studio 中查看队列的内容。Expand the Queues node, and then double-click the queue named outqueue to view the contents of the queue in Visual Studio.

    此队列包含在运行 HTTP 触发的函数时队列输出绑定创建的消息。The queue contains the message that the queue output binding created when you ran the HTTP-triggered function. 如果使用 Azure 的默认 name 值调用了此函数,则队列消息为“传递给函数的名称: Azure”。If you invoked the function with the default name value of Azure, the queue message is Name passed to the function: Azure.

    Azure 存储资源管理器中显示的队列消息

  4. 再次运行函数,发送另一个请求,此时会看到新消息出现在队列中。Run the function again, send another request, and you'll see a new message appear in the queue.

现在,可将更新的函数应用重新发布到 Azure。Now, it's time to republish the updated function app to Azure.

重新部署并验证更新的应用Redeploy and verify the updated app

  1. 在“解决方案资源管理器”中,右键单击项目并选择“发布”,然后选择“发布”将项目重新发布到 Azure。 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. 如前所述,请在 URL 的后面追加查询字符串 &name=<yourname>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 have created in this quickstart, do not clean up the resources.

Azure 中的资源是指函数应用、函数、存储帐户等。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 created resources to complete these quickstarts. 这些资源可能需要付费,具体取决于帐户状态服务定价You may 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. 在 Azure 门户中转到“资源组”页。 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.

    从函数应用页选择要删除的资源组。

    若要从仪表板转到该页,请选择“资源组”,然后选择用于本快速入门的资源组。 To get to that page from the dashboard, select Resource groups, and then select the resource group that you used for this quickstart.

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

现已更新 HTTP 触发的函数,使其将数据写入存储队列。You've updated your HTTP triggered function to write data to a Storage queue. 若要详细了解如何开发 Functions,请参阅使用 Visual Studio 开发 Azure FunctionsTo learn more about developing Functions, see Develop Azure Functions using Visual Studio.