使用 Visual Studio 开发 Azure FunctionsDevelop Azure Functions using Visual Studio

用于 Visual Studio 2017 的 Azure Functions 工具是 Visual Studio 的一个扩展,可用于开发、测试 C# 函数并将其部署到 Azure。Azure Functions Tools for Visual Studio 2017 is an extension for Visual Studio that lets you develop, test, and deploy C# functions to Azure. 如果这是你第一次体验 Azure Functions,可以在 Azure Functions 简介中了解详细信息。If this experience is your first with Azure Functions, you can learn more at An introduction to Azure Functions.

Azure Functions 工具提供以下优势:The Azure Functions Tools provides the following benefits:

  • 在本地开发计算机上编辑、生成和运行函数。Edit, build, and run functions on your local development computer.
  • 将 Azure Functions 项目直接发布到 Azure。Publish your Azure Functions project directly to Azure.
  • 使用 Web 作业属性在 C# 代码中直接声明函数绑定,而无需单独维护绑定定义的 function.json。Use WebJobs attributes to declare function bindings directly in the C# code instead of maintaining a separate function.json for binding definitions.
  • 开发和部署预先编译的 C# 函数。Develop and deploy pre-compiled C# functions. 与基于 C# 脚本的函数相比,预先编译的函数的冷启动性能更好。Pre-complied functions provide a better cold-start performance than C# script-based functions.
  • 可以在 C# 中编写函数的代码,同时利用 Visual Studio 开发环境的所有优势。Code your functions in C# while having all of the benefits of Visual Studio development.

本文详细介绍了如何使用 Azure Functions Tools for Visual Studio 2017 开发 C# 函数并将其发布到 Azure。This article provides details about how to use the Azure Functions Tools for Visual Studio 2017 to develop C# functions and publish them to Azure. 在阅读本文之前,应先完成 Visual Studio 的函数快速入门Before you read this article, you should complete the Functions quickstart for Visual Studio.

Important

不要将本地开发和门户开发混合在同一函数应用中。Don't mix local development with portal development in the same function app. 从本地项目发布到函数应用时,部署过程会覆盖在门户中开发的任何函数。When you publish from a local project to a function app, the deployment process overwrites any functions that you developed in the portal.

先决条件Prerequisites

Azure Functions 工具包含在 Visual Studio 2017 版本 15.5 或更高版本的 Azure 开发工作负荷中。Azure Functions Tools is included in the Azure development workload of Visual Studio 2017 version 15.5, or a later version. 请确保你在安装 Visual Studio 2017 时随附了Azure 开发工作负荷:Make sure you include the Azure development workload in your Visual Studio 2017 installation:

使用 Azure 开发工作负荷安装 Visual Studio 2017

请确保 Visual Studio 为最新版本,并且使用的是最新版本的 Azure Functions 工具。Make sure that your Visual Studio is up-to-date and that you are using the most recent version of the Azure Functions tools.

其他要求Other requirements

若要创建和部署函数,还需要:To create and deploy functions, you also need:

  • 一个有效的 Azure 订阅。An active Azure subscription. 如果没有 Azure 订阅,可以使用试用帐户If you don't have an Azure subscription, Trials account are available.

  • 一个 Azure 存储帐户。An Azure Storage account. 若要创建存储帐户,请参阅创建存储帐户To create a storage account, see Create a storage account.

检查工具版本Check your tools version

  1. 在“工具”菜单中,选择“扩展和更新”。From the Tools menu, choose Extensions and Updates. 展开“已安装” > “工具”,选择“Azure Functions 和 Web 作业工具”。Expand Installed > Tools and choose Azure Functions and Web Jobs Tools.

    验证 Functions 工具版本

  2. 请注意已安装的版本Note the installed Version. 可以将此版本与发行说明中列出的最新版本进行比较。You can compare this version with the latest version listed in the release notes.

  3. 如果你的版本较旧,可以在 Visual Studio 中更新工具,如以下部分中所示。If your version is older, update your tools in Visual Studio as shown in the following section.

更新工具Update your tools

  1. 在“扩展和更新”对话框中,展开“更新” > “Visual Studio Marketplace”,依次选择“Azure Functions 和 Web 作业工具”和“更新”。In the Extensions and Updates dialog, expand Updates > Visual Studio Marketplace, choose Azure Functions and Web Jobs Tools and select Update.

    更新 Functions 工具版本

  2. 下载工具更新后,请关闭 Visual Studio 以触发使用 VSIX 安装程序的工具更新。After the tools update is downloaded, close Visual Studio to trigger the tools update using the VSIX installer.

  3. 在安装程序中,选择“确定”以启动,然后单击“修改”以更新工具。In the installer, choose OK to start and then Modify to update the tools.

  4. 更新完成后,请选择“关闭”并重启 Visual Studio。After the update is complete, choose Close and restart Visual Studio.

创建 Azure Functions 项目Create an Azure Functions project

Visual Studio 中的 Azure Functions 项目模板创建一个项目,该项目可发布到 Azure 中的函数应用。The Azure Functions project template in Visual Studio creates a project that can be published to a function app in Azure. 可使用函数应用将函数分组为一个逻辑单元,以用于管理、部署和共享资源。You can use a function app to group functions as a logical unit for management, deployment, and sharing of resources.

  1. 在 Visual Studio 的“文件”菜单中,依次选择“新建” > “项目”。In Visual Studio, on the File menu, select New > Project.

  2. 在“新建项目”对话框中,依次选择“已安装” > “Visual C#” > “云” > “Azure Functions”。In the New Project dialog box, select Installed > Visual C# > Cloud > Azure Functions. 输入项目的名称,并选择“确定”。Enter a name for your project, and select OK. 函数应用名称必须可以充当 C# 命名空间,因此请勿使用下划线、连字符或任何其他的非字母数字字符。The function app name must be valid as a C# namespace, so don't use underscores, hyphens, or any other nonalphanumeric characters.

    “新建项目”对话框,用于在 Visual Studio 中创建函数

  3. 使用图像后的表中指定的设置。Use the settings specified in the table that follows the image.

    Visual Studio 中的“新建函数”对话框

    设置Setting 建议的值Suggested value DescriptionDescription
    版本Version Azure Functions 2.xAzure Functions 2.x
    (.NET Core)(.NET Core)
    此设置创建使用 Azure Functions 运行时版本 2.x(支持 .NET Core)的函数项目。This setting creates a function project that uses the version 2.x runtime of Azure Functions, which supports .NET Core. Azure Functions 1.x 支持 .NET Framework。Azure Functions 1.x supports the .NET Framework. 有关详细信息,请参阅面向 Azure Functions 运行时版本For more information, see Target Azure Functions runtime version.
    模板Template HTTP 触发器HTTP trigger 此设置创建由 HTTP 请求触发的函数。This setting creates a function triggered by an HTTP request.
    存储帐户Storage account 存储模拟器Storage emulator HTTP 触发器不使用 Azure 存储帐户连接。An HTTP trigger doesn't use the Azure Storage account connection. 所有其他触发器类型需要有效的存储帐户连接字符串。All other trigger types require a valid Storage account connection string.
    访问权限Access rights 匿名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. 有关密钥和授权的详细信息,请参阅 HTTP 和 Webhook 绑定中的授权密钥For more information about keys and authorization, see Authorization keys in the HTTP and webhook bindings.

    Note

    确保将“访问权限”设置为 AnonymousMake sure you set the Access rights to Anonymous. 如果选择默认级别为 Function,需要在请求中提供函数密钥才能访问函数终结点。If you choose the default level of Function, you're required to present the function key in requests to access your function endpoint.

  4. 选择“确定”以创建函数项目和 HTTP 触发的函数。Select OK to create the function project and HTTP-triggered function.

此项目模板创建 C# 项目,安装 Microsoft.NET.Sdk.Functions NuGet 包,并设置目标框架。The project template creates a C# project, installs the Microsoft.NET.Sdk.Functions NuGet package, and sets the target framework. Functions 1.x 面向 .NET Framework,而 Functions 2.x 则面向 .NET Standard。Functions 1.x targets the .NET Framework, and Functions 2.x targets .NET Standard. 新项目包含以下文件:The new project has the following files:

  • host.json:用于配置 Functions 主机。host.json: Lets you configure the Functions host. 在本地和 Azure 中运行时,都会应用这些设置。These settings apply both when running locally and in Azure. 有关详细信息,请参阅 host.json 参考For more information, see host.json reference.

  • local.settings.json:维护本地运行函数时使用的设置。local.settings.json: Maintains settings used when running functions locally. Azure 不使用这些设置,它们由 Azure Functions 核心工具使用。These settings are not used by Azure, they are used by the Azure Functions Core Tools. 使用此文件为函数所需的变量指定应用设置。Use this file to specify app settings for variables required by your functions. 针对项目中的函数绑定所需的每个连接,将新项添加到 Values 数组。Add a new item to the Values array for each connection required by the functions bindings in your project. 有关详细信息,请参阅“Azure Functions 核心工具”一文中的本地设置文件For more information, see Local settings file in the Azure Functions Core Tools article.

    Important

    由于 local.settings.json 文件可能包含机密,因此必须将其从项目源代码管理中排除。Because the local.settings.json file can contain secrets, you must excluded it from your project source control. 此文件的“复制到输出目录”设置应始终为“如果较新则复制”。The Copy to Output Directory setting for this file should always be Copy if newer.

有关详细信息,请参阅 Functions 类库项目For more information, see Functions class library project.

为本地开发配置项目Configure the project for local development

Functions 运行时在内部使用 Azure 存储帐户。The Functions runtime uses an Azure Storage account internally. 对于除 HTTP 和 Webhook 以外的所有触发器类型,必须将 Values.AzureWebJobsStorage 键设置为有效的 Azure 存储帐户连接字符串。For all trigger types other than HTTP and webhooks, you must set the Values.AzureWebJobsStorage key to a valid Azure Storage account connection string. 函数应用还可以在项目所需的 AzureWebJobsStorage 连接设置中使用 Azure 存储模拟器Your function app can also use the Azure storage emulator for the AzureWebJobsStorage connection setting that is required by the project. 若要使用模拟器,请将 AzureWebJobsStorage 的值设置为 UseDevelopmentStorage=trueTo use the emulator, set the value of AzureWebJobsStorage to UseDevelopmentStorage=true. 在部署之前,必须将此设置更改为实际的存储连接。You must change this setting to an actual storage connection before deployment.

若要设置存储帐户连接字符串,请执行以下操作:To set the storage account connection string:

  1. 在 Visual Studio 中,打开“Cloud Explorer”,展开“存储帐户” > “你的存储帐户”,然后选择“属性面板”并复制“主连接字符串”值。In Visual Studio, open Cloud Explorer, expand Storage Account > Your Storage Account, then select Properties and copy the Primary Connection String value.

  2. 在项目内,打开 local.settings.json 项目文件,并将“AzureWebJobsStorage”键的值设置为复制的连接字符串。In your project, open the local.settings.json file and set the value of the AzureWebJobsStorage key to the connection string you copied.

  3. 重复上述步骤,将唯一键添加到函数所需的其他任何连接的 Values 数组。Repeat the previous step to add unique keys to the Values array for any other connections required by your functions.

将函数添加到项目Add a function to your project

在预先编译的函数中,可以通过在代码中应用属性来定义函数使用的绑定。In pre-compiled functions, the bindings used by the function are defined by applying attributes in the code. 使用 Azure Functions 工具通过提供的模板创建函数时,系统会自动应用这些属性。When you use the Azure Functions Tools to create your functions from the provided templates, these attributes are applied for you.

  1. 在“解决方案资源管理器”中,右键单击项目节点,然后选择“添加” > “新建项”。In Solution Explorer, right-click on your project node and select Add > New Item. 选择“Azure 函数”,键入类的名称,然后单击“添加”。Select Azure Function, type a Name for the class, and click Add.

  2. 选择你的触发器,设置绑定属性,然后单击“创建”。Choose your trigger, set the binding properties, and click Create. 以下示例显示创建队列存储触发的函数时的设置。The following example shows the settings when creating a Queue storage triggered function.

    创建队列触发的函数

    此触发器示例使用具有名为 QueueStorage 的键的连接字符串。This trigger example uses a connection string with a key named QueueStorage. 必须在 local.settings.json 文件中定义此连接字符串设置。This connection string setting must be defined in the local.settings.json file.

  3. 检查新添加的类。Examine the newly added class. 将会看到一个静态 Run 方法,它已使用 FunctionName 属性设置了属性。You see a static Run method, that is attributed with the FunctionName attribute. 该属性指示该方法是函数的入口点。This attribute indicates that the method is the entry point for the function.

    例如,以下 C# 类表示一个基本的队列存储触发的函数:For example, the following C# class represents a basic Queue storage triggered function:

    using System;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Host;
    using Microsoft.Extensions.Logging;
    
    namespace FunctionApp1
    {
        public static class Function1
        {
            [FunctionName("QueueTriggerCSharp")]
            public static void Run([QueueTrigger("myqueue-items", Connection = "QueueStorage")]string myQueueItem, ILogger log)
            {
                log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
            }
        }
    }
    

    已向提供给入口点方法的每个绑定参数提供了特定于绑定的属性。A binding-specific attribute is applied to each binding parameter supplied to the entry point method. 该属性采用绑定信息作为参数。The attribute takes the binding information as parameters. 在上例中,第一个参数具应用了 QueueTrigger 属性,表示触发了队列的函数。In the previous example, the first parameter has a QueueTrigger attribute applied, indicating queue triggered function. 队列名称和连接字符串设置名称作为参数传递到“QueueTrigger”属性。The queue name and connection string setting name are passed as parameters to the QueueTrigger attribute. 有关详细信息,请参阅 Azure Functions 的 Azure 队列存储绑定For more information, see Azure Queue storage bindings for Azure Functions.

可以使用上述过程向函数应用项目添加更多的函数。You can use the above procedure to add more functions to your function app project. 项目中的每个函数可以有不同的触发器,但每个函数的触发器必须刚好一个。Each function in the project can have a different trigger, but a function must have exactly one trigger. 有关详细信息,请参阅 Azure Functions 触发器和绑定概念For more information, see Azure Functions triggers and bindings concepts.

添加绑定Add bindings

使用触发器时,输入和输出绑定是作为绑定属性添加到函数的。As with triggers, input and output bindings are added to your function as binding attributes. 向函数添加绑定,如下所示:Add bindings to a function as follows:

  1. 确保已为本地开发配置项目Make sure you have configured the project for local development.

  2. 为特定绑定添加适当的 NuGet 扩展包。Add the appropriate NuGet extension package for the specific binding. 有关详细信息,请参阅“触发器和绑定”一文中的使用 Visual Studio 进行本地 C# 开发For more information, see Local C# development using Visual Studio in the Triggers and Bindings article. 特定于绑定的 NuGet 包要求位于绑定的参考文章中。The binding-specific NuGet package requirements are found in the reference article for the binding. 例如,可以在事件中心绑定参考文章中找到事件中心触发器的包要求。For example, find package requirements for the Event Hubs trigger in the Event Hubs binding reference article.

  3. 如果有绑定需要的应用设置,请将其添加到本地设置文件中的 Values 集合。If there are app settings that the binding needs, add them to the Values collection in the local setting file. 当函数在本地运行时,会使用这些值。These values are used when the function runs locally. 当函数在 Azure 的函数应用中运行时,会使用函数应用设置When the function runs in the function app in Azure, the function app settings are used.

  4. 将适当的绑定属性添加到方法签名。Add the appropriate binding attribute to the method signature. 在以下示例中,一条队列消息触发了该函数,而输出绑定则创建了一条新的队列消息,在不同的队列中使用了相同的文本。In the following example, a queue message triggers the function, and the output binding creates a new queue message with the same text in a different queue.

    public static class SimpleExampleWithOutput
    {
        [FunctionName("CopyQueueMessage")]
        public static void Run(
            [QueueTrigger("myqueue-items-source", Connection = "AzureWebJobsStorage")] string myQueueItem, 
            [Queue("myqueue-items-destination", Connection = "AzureWebJobsStorage")] out string myQueueItemCopy,
            ILogger log)
        {
            log.LogInformation($"CopyQueueMessage function processed: {myQueueItem}");
            myQueueItemCopy = myQueueItem;
        }
    }
    

    到队列存储的连接从 AzureWebJobsStorage 设置获取。The connection to Queue storage is obtained from the AzureWebJobsStorage setting. 有关详细信息,请参阅特定绑定的参考文章。For more information, see the reference article for the specific binding.

下表显示了 Azure Functions 运行时的两个主要版本支持的绑定。The following table shows the bindings that are supported in the two major versions of the Azure Functions runtime.

类型Type 1.x1.x 2.x12.x1 触发器Trigger 输入Input 输出Output
Blob 存储Blob Storage
Cosmos DBCosmos DB
事件中心Event Hubs
HTTP 和 WebhookHTTP & Webhooks
Microsoft Graph
Excel 表
Microsoft Graph
Excel tables
Microsoft Graph
OneDrive 文件
Microsoft Graph
OneDrive files
Microsoft Graph
Outlook 电子邮件
Microsoft Graph
Outlook email
Microsoft Graph
事件
Microsoft Graph
Events
Microsoft Graph
身份验证令牌
Microsoft Graph
Auth tokens
移动应用Mobile Apps
通知中心Notification Hubs
队列存储Queue storage
SendGridSendGrid
服务总线Service Bus
表存储Table storage
计时器Timer

1 在 2.x 中,除了 HTTP 和 Timer 以外,所有绑定都必须注册。1 In 2.x, all bindings except HTTP and Timer must be registered. 请参阅注册绑定扩展See Register binding extensions.

测试函数Testing functions

Azure Functions Core Tools 允许在本地开发计算机上运行 Azure Functions 项目。Azure Functions Core Tools lets you run Azure Functions project on your local development computer. 首次从 Visual Studio 启动某个函数时,系统会提示你安装这些工具。You are prompted to install these tools the first time you start a function from Visual Studio.

若要测试函数,请按 F5。To test your function, press F5. 如果系统提示,请按 Visual Studio 的请求下载和安装 Azure Functions Core (CLI) 工具。If prompted, accept the request from Visual Studio to download and install Azure Functions Core (CLI) tools. 可能还需启用一个防火墙例外,以便这些工具能够处理 HTTP 请求。You may also need to enable a firewall exception so that the tools can handle HTTP requests.

在运行项目时,可以像测试已部署的函数一样测试代码。With the project running, you can test your code as you would test deployed function. 有关详细信息,请参阅在 Azure Functions 中测试代码的策略For more information, see Strategies for testing your code in Azure Functions. 在调试模式下运行时,断点将按预期命中 Visual Studio。When running in debug mode, breakpoints are hit in Visual Studio as expected.

若要详细了解如何使用 Azure Functions 核心工具,请参阅在本地编写 Azure 函数代码并对其进行测试To learn more about using the Azure Functions Core Tools, see Code and test Azure functions locally.

发布到 AzurePublish to Azure

  1. 在“解决方案资源管理器” 中,右键单击该项目并选择“发布”。In Solution Explorer, right-click the project and select Publish.

  2. 依次选择“Azure Function App”、“新建”、“发布”。Select Azure Function App, choose Create New, and then select Publish.

    选取发布目标

    启用“从 Zip 运行”后,Azure 中的函数应用将进入只读模式,并且会直接从部署包运行。When you enable Run from Zip, your function app in Azure goes into read-only mode and is run directly from the deployment package. 有关详细信息,请参阅从包文件运行 Azure FunctionsFor more information, see Run your Azure Functions from a package file.

    Caution

    选择“选择现有”时,Azure 中现有函数应用中的所有文件都将被本地项目中的文件覆盖。When you choose Select Existing, all files in the existing function app in Azure are overwritten by files from the local project. 仅在将更新重新发布到现有函数应用时才使用此选项。Only use this option when republishing updates to an existing function app.

  3. 如果尚未将 Visual Studio 连接到 Azure 帐户,请选择“添加帐户...”。If you haven't already connected Visual Studio to your Azure account, select Add an account....

  4. 在“创建应用服务”对话框中,使用在图片下方的表中指定的“托管”设置:In the Create App Service dialog, use the Hosting settings as specified in the table below the image:

    “创建应用服务”对话框

    设置Setting 建议的值Suggested value 说明Description
    应用名称App Name 全局唯一名称Globally unique name 用于唯一标识新 Function App 的名称。Name that uniquely identifies your new function app.
    订阅Subscription 选择订阅Choose your subscription 要使用的 Azure 订阅。The Azure subscription to use.
    资源组Resource Group MyResourceGroupmyResourceGroup 要在其中创建 Function App 的资源组的名称。Name of the resource group in which to create your function app. 选择“新建”创建新的资源组。Choose New to create a new resource group.
    应用服务计划App Service Plan 消耗量计划Consumption plan 单击“新建”创建某个无服务器计划后,确保在“大小”下选择“消耗量”。Make sure to choose the Consumption under Size after you click New to create a serverless plan. 此外,选择离你近或离函数访问的其他服务近的区域中的位置Also, choose a Location in a region near you or near other services your functions access. 在“消耗量”之外的计划中运行时,必须管理函数应用的缩放When you run in a plan other than Consumption, you must manage the scaling of your function app.
    存储帐户Storage Account 常规用途存储帐户General purpose storage account Functions 运行时需要 Azure 存储帐户。An Azure storage account is required by the Functions runtime. 单击“新建”创建一个常规用途存储帐户。Click New to create a general purpose storage account. 也可使用符合存储帐户要求的现有帐户。You can also use an existing account that meets the storage account requirements.
  5. 单击“创建”以使用这些设置在 Azure 中创建函数应用和相关资源,并部署函数项目代码。Click Create to create a function app and related resources in Azure with these settings and deploy your function project code.

  6. 完成部署后,请记下“站点 URL”值,这是函数应用在 Azure 中的地址。After the deployment is complete, make a note of the Site URL value, which is the address of your function app in Azure.

    发布成功消息

函数应用设置Function app settings

还必须将在 local.settings.json 中添加的任何设置添加到 Azure 函数应用中。Any settings you added in the local.settings.json must be also added to the function app in Azure. 发布项目时,不会自动上传这些设置。These settings are not uploaded automatically when you publish the project.

将所需设置上传到 Azure 中的函数应用的最简单方法是使用“管理应用程序设置...”链接(在成功发布项目之后显示)。The easiest way to upload the required settings to your function app in Azure is to use the Manage Application Settings... link that is displayed after you successfully publish your project.

这会显示用于函数应用的“应用程序设置”对话框,可以在其中添加新应用程序设置或修改现有设置。This displays the Application Settings dialog for the function app, where you can add new application settings or modify existing ones.

本地表示 local.settings.json 文件中的设置值,远程是 Azure 的函数应用中的当前设置。Local represents a setting value in the local.settings.json file, and Remote is the current setting in the function app in Azure. 选择“添加设置”以创建新的应用设置。Choose Add setting to create a new app setting. 使用“从本地插入值”链接将设置值复制到“远程”字段。Use the Insert value from Local link to copy a setting value to the Remote field. 你选择“确定”后,挂起的更改将写入本地设置文件和函数应用。Pending changes are written to the local settings file and the function app when you select OK.

还可以采用以下这些其他方法之一来管理应用程序设置:You can also manage application settings in one of these other ways:

后续步骤Next steps

若要详细了解 Azure Functions 核心工具,请参阅在本地编写 Azure 函数代码并对其进行测试To learn more about the Azure Functions Core Tools, see Code and test Azure functions locally.

若要了解有关以 .NET 类库开发函数的详细信息,请参阅 Azure Functions C# 开发人员参考To learn more about developing functions as .NET class libraries, see Azure Functions C# developer reference. 本文还举例说明了如何使用属性来声明 Azure Functions 支持的各种类型的绑定。This article also links to examples of how to use attributes to declare the various types of bindings supported by Azure Functions.