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

使用 适用于 Visual Studio Code 的 Azure Functions 扩展可在本地开发函数并将其部署到 Azure。The Azure Functions extension for Visual Studio Code lets you locally develop functions and deploy them 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 extension provides these benefits:

  • 在本地开发计算机上编辑、生成和运行函数。Edit, build, and run functions on your local development computer.
  • 将 Azure Functions 项目直接发布到 Azure。Publish your Azure Functions project directly to Azure.
  • 以各种语言编写函数,同时利用 Visual Studio Code 的优势。Write your functions in various languages while taking advantage of the benefits of Visual Studio Code.

该扩展可与 Azure Functions 运行时版本 2.x(及以上)支持的以下语言配合使用:The extension can be used with the following languages, which are supported by the Azure Functions runtime starting with version 2.x:

*要求将 C# 脚本设置为默认的项目语言*Requires that you set C# script as your default project language.

本文中的示例当前仅适用于 JavaScript (Node.js) 和 C# 类库函数。In this article, examples are currently available only for JavaScript (Node.js) and C# class library functions.

本文详细介绍如何使用 Azure Functions 扩展开发函数并将其发布到 Azure。This article provides details about how to use the Azure Functions extension to develop functions and publish them to Azure. 在阅读本文之前,应使用 Visual Studio Code 创建第一个函数Before you read this article, you should create your first function by using Visual Studio Code.

重要

不要对单个函数应用混合使用本地开发和门户开发。Don't mix local development and portal development for a single 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 扩展之前,必须符合以下要求:Before you install and run the Azure Functions extension, you must meet these requirements:

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

所需的其他资源(例如 Azure 存储帐户)将在使用 Visual Studio Code 发布时在订阅中创建。Other resources that you need, like an Azure storage account, are created in your subscription when you publish by using Visual Studio Code.

重要

可以在本地开发函数并将其发布到 Azure,而无需在本地启动并运行它们。You can develop functions locally and publish them to Azure without having to start and run them locally. 若要在本地运行函数,需要满足其他一些要求,包括自动下载 Azure Functions Core Tools。To run your functions locally, you'll need to meet some additional requirements, including an automatic download of Azure Functions Core Tools. 有关详细信息,请参阅在本地运行项目的其他要求To learn more, see Additional requirements for running a project locally.

安装 Azure Functions 扩展Install the Azure Functions extension

可以使用 Azure Functions 扩展创建和测试函数,并将其部署到 Azure。You can use the Azure Functions extension to create and test functions and deploy them to Azure.

  1. 在 Visual Studio Code 中打开“扩展” 并搜索 azure functions,或者在 Visual Studio Code 中选择此链接In Visual Studio Code, open Extensions and search for azure functions, or select this link in Visual Studio Code.

  2. 选择“安装” 以安装 Visual Studio Code 的扩展:Select Install to install the extension for Visual Studio Code:

    安装适用于 Azure Functions 的扩展

  3. 安装后,在活动栏上选择 Azure 图标。After installation, select the Azure icon on the Activity bar. 此时侧边栏中应显示 Azure Functions 区域。You should see an Azure Functions area in the Side Bar.

    侧边栏中的 Azure Functions 区域

创建 Azure Functions 项目Create an Azure Functions project

使用 Functions 扩展可以创建函数应用项目以及第一个函数。The Functions extension lets you create a function app project, along with your first function. 以下步骤说明如何在新的 Functions 项目中创建 HTTP 触发的函数。The following steps show how to create an HTTP-triggered function in a new Functions project. HTTP 触发器是用于演示的最简单函数触发器模板。HTTP trigger is the simplest function trigger template to demonstrate.

  1. Azure:Functions 中,选择“创建函数”图标:From Azure: Functions, select the Create Function icon:

    创建函数

  2. 选择函数应用项目所在的文件夹,然后选择函数项目的语言Select the folder for your function app project, and then Select a language for your function project.

  3. 如果尚未安装 Core Tools,系统会要求你选择要安装的 Core Tools 版本If you haven't already installed the Core Tools, you are asked to Select a version of the Core Tools to install. 选择版本 2.x 或更高版本。Choose version 2.x or a later version.

  4. 选择“HTTP 触发器”函数模板,或者可以选择“暂时跳过”以创建不带函数的项目。 Select the HTTP trigger function template, or you can select Skip for now to create a project without a function. 以后始终可以将函数添加到项目You can always add a function to your project later.

    选择 HTTP 触发器模板

  5. 键入“HttpExample”作为函数名称,按 Enter,然后选择“函数”授权。Type HttpExample for the function name and select Enter, and then select Function authorization. 调用函数终结点时,此授权级别需要提供函数密钥This authorization level requires you to provide a function key when you call the function endpoint.

    选择“函数”授权

    此时将使用 HTTP 触发的函数的模板,以所选语言创建函数。A function is created in your chosen language and in the template for an HTTP-triggered function.

    Visual Studio Code 中的 HTTP 触发的函数模板

生成的项目文件Generated project files

项目模板将以所选语言创建一个项目,并安装所需的依赖项。The project template creates a project in your chosen language and installs required dependencies. 对于任何语言,新项目包含以下文件:For any language, the new project has these files:

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

  • local.settings.json:维护本地运行函数时使用的设置。local.settings.json: Maintains settings used when you're running functions locally. 仅当在本地运行函数时,才使用这些设置。These settings are used only when you're running functions locally. 有关详细信息,请参阅本地设置文件For more information, see Local settings file.

    重要

    由于 local.settings.json 文件可能包含机密,因此需要将其从项目源代码管理中排除。Because the local.settings.json file can contain secrets, you need to exclude it from your project source control.

根据你的语言,将创建以下其他文件:Depending on your language, these other files are created:

此时,可以通过将参数添加到 C# 类库函数,将输入和输出绑定添加到函数。At this point, you can add input and output bindings to your function by adding a parameter to a C# class library function.

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

可以使用某个预定义的函数触发器模板将新函数添加到现有项目。You can add a new function to an existing project by using one of the predefined Functions trigger templates. 若要添加新的函数触发器,请按 F1 打开命令面板,然后搜索并运行命令“Azure Functions:创建函数”。To add a new function trigger, select F1 to open the command palette, and then search for and run the command Azure Functions: Create Function. 遵照提示选择触发器类型,并定义触发器的所需属性。Follow the prompts to choose your trigger type and define the required attributes of the trigger. 如果触发器需要访问密钥或连接字符串才能连接到服务,请在创建函数触发器之前做好准备。If your trigger requires an access key or connection string to connect to a service, get it ready before you create the function trigger.

此操作的结果取决于项目语言:The results of this action depend on your project's language:

将新的 C# 类库 (.cs) 文件添加到项目。A new C# class library (.cs) file is added to your project.

添加输入和输出绑定Add input and output bindings

可以通过添加输入和输出绑定来扩展函数。You can expand your function by adding input and output bindings. 添加绑定的过程取决于项目的语言。The process for adding bindings depends on your project's language. 有关绑定的详细信息,请参阅 Azure Functions 触发器和绑定的概念To learn more about bindings, see Azure Functions triggers and bindings concepts.

以下示例连接到名为 outqueue 的存储队列,其中,存储帐户的连接字符串已在 local.settings.json 中的 MyStorageConnection 应用程序设置内进行设置。The following examples connect to a storage queue named outqueue, where the connection string for the storage account is set in the MyStorageConnection application setting in local.settings.json.

更新函数方法,将以下参数添加到 Run 方法定义:Update the function method to add the following parameter to the Run method definition:

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

此代码要求添加以下 using 语句:This code requires you to add the following using statement:

using Microsoft.Azure.WebJobs.Extensions.Storage;

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. 将一个或多个消息添加到集合。You add one or more messages to the collection. 函数完成后,这些消息将发送到队列。These messages are sent to the queue when the function completes.

有关详细信息,请参阅队列存储输出绑定文档。To learn more, see the Queue storage output binding documentation.

下表显示了 Azure Functions 运行时的主版本支持的绑定:This table shows the bindings that are supported in the major versions of the Azure Functions runtime:

类型Type 1.x1.x 2.x 及更高版本12.x and higher1 触发器Trigger 输入Input 输出Output
Blob 存储Blob storage
Cosmos DBCosmos DB
事件网格Event Grid
事件中心Event Hubs
HTTP 和 WebhookHTTP & webhooks
IoT 中心IoT Hub
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
SignalRSignalR
表存储Table storage
计时器Timer

1 从版本 2.x 运行时开始,除了 HTTP 和 Timer 以外,所有绑定都必须注册。1 Starting with the version 2.x runtime, all bindings except HTTP and Timer must be registered. 请参阅注册绑定扩展See Register binding extensions.

登录 AzureSign in to Azure

在发布应用之前,必须先登录到 Azure。Before you can publish your app, you must sign in to Azure.

  1. 打开 Visual Studio Code,然后单击 View -> Command Palette...Open Visual Studio Code, click View -> Command Palette....

  2. 输入 Sign In to Azure Cloud,以搜索 Azure 中国环境。Input Sign In to Azure Cloud to search Azure China Environment.

  3. 在搜索结果中单击 Azure ChinaClick Azure China in search result.

  4. 窗口的右下角将出现一个弹出窗口。You will find a popup window at the bottom right of your window.

    弹出窗口

  5. 打开页面 **https://microsoft.com/deviceloginchina**,然后输入该代码进行身份验证。Open the page https://microsoft.com/deviceloginchina and enter the code to authenticate.

发布到 AzurePublish to Azure

使用 Visual Studio Code 可以将 Functions 项目直接发布到 Azure。Visual Studio Code lets you publish your Functions project directly to Azure. 在此过程中,将在 Azure 订阅中创建函数应用和相关的资源。In the process, you create a function app and related resources in your Azure subscription. 函数应用为函数提供了执行上下文。The function app provides an execution context for your functions. 该项目将打包并部署到 Azure 订阅中的新函数应用。The project is packaged and deployed to the new function app in your Azure subscription.

当你从 Visual Studio Code 发布到 Azure 中的新函数应用时,将为你提供快速函数应用创建路径和高级路径。When you publish from Visual Studio Code to a new function app in Azure, you are offered both a quick function app create path and an advanced path.

从 Visual Studio Code 发布时,可以利用 Zip 部署技术。When you publish from Visual Studio Code, you take advantage of the Zip deploy technology.

快速函数应用创建Quick function app create

当你选择“+ 在 Azure 中创建新的函数应用...”时,扩展会自动为函数应用所需的 Azure 资源生成值。When you choose + Create new function app in Azure..., the extension automatically generates values for the Azure resources needed by your function app. 这些值基于所选的函数应用名称。These values are based on the function app name that you choose. 有关使用默认值将项目发布到 Azure 中的新函数应用的示例,请参阅 Visual Studio Code 快速入门文章For an example of using defaults to publish your project to a new function app in Azure, see the Visual Studio Code quickstart article.

如果要为创建的资源提供显式名称,则必须选择高级创建路径。If you want to provide explicit names for the created resources, you must choose the advanced create path.

使用高级选项将项目发布到 Azure 中的新函数应用Publish a project to a new function app in Azure by using advanced options

以下步骤使用高级创建选项将项目发布到创建的新函数应用:The following steps publish your project to a new function app created with advanced create options:

  1. 在“Azure: Functions”区域中,选择“部署到函数应用”图标。In the Azure: Functions area, select the Deploy to Function App icon.

    函数应用设置

  2. 如果你未登录,系统会提示“登录到 Azure”。If you're not signed in, you're prompted to Sign in to Azure. 也可以创建一个 Azure 帐户You can also Create a Azure account. 从浏览器登录后,返回到 Visual Studio Code。After signing in from the browser, go back to Visual Studio Code.

  3. 如果你有多个订阅,请为函数应用选择一个订阅,然后选择“+ 在 Azure 中创建新的函数应用...”“高级”If you have multiple subscriptions, Select a subscription for the function app, and then select + Create New Function App in Azure... Advanced. 使用此“高级”选项可以更好地控制在 Azure 中创建的资源。This Advanced option gives you more control over the resources you create in Azure.

  4. 按提示操作并提供以下信息:Following the prompts, provide this information:

    PromptPrompt ValueValue 说明Description
    选择 Azure 中的函数应用Select function app in Azure 在 Azure 中创建新的函数应用Create New Function App in Azure 在下一个提示中,键入用于标识新函数应用的全局唯一名称,然后按 Enter。At the next prompt, type a globally unique name that identifies your new function app and then select Enter. 函数应用名称的有效字符包括 a-z0-9-Valid characters for a function app name are a-z, 0-9, and -.
    选择 OSSelect an OS WindowsWindows 函数应用在 Windows 上运行。The function app runs on Windows.
    选择托管计划Select a hosting plan 消耗计划Consumption plan 使用无服务器消耗计划托管A serverless Consumption plan hosting is used.
    选择新应用的运行时Select a runtime for your new app 项目语言Your project language 该运行时必须与要发布的项目相匹配。The runtime must match the project that you're publishing.
    选择新资源的资源组Select a resource group for new resources 创建新的资源组Create New Resource Group 在下一个提示中,键入资源组名称(例如 myResourceGroup),然后按 Enter。At the next prompt, type a resource group name, like myResourceGroup, and then select enter. 也可以选择现有的资源组。You can also select an existing resource group.
    选择存储帐户Select a storage account 新建存储帐户Create new storage account 在下一个提示中,键入函数应用使用的新存储帐户的全局唯一名称,然后按 Enter。At the next prompt, type a globally unique name for the new storage account used by your function app and then select Enter. 存储帐户名称长度必须为 3 到 24 个字符,只能包含数字和小写字母。Storage account names must be between 3 and 24 characters long and can contain only numbers and lowercase letters. 也可以选择现有的帐户。You can also select an existing account.
    选择新资源的位置Select a location for new resources regionregion 在与你靠近或者与函数要访问的其他服务靠近的区域中选择一个位置。Select a location in a region near you or near other services that your functions access.

    创建函数应用并应用了部署包之后,会显示一个通知。A notification appears after your function app is created and the deployment package is applied. 在此通知中选择“查看输出”以查看创建和部署结果,其中包括你创建的 Azure 资源。Select View Output in this notification to view the creation and deployment results, including the Azure resources that you created.

重新发布项目文件Republish project files

重要

发布到现有函数应用将覆盖该应用在 Azure 中的内容。Publishing to an existing function app overwrites the content of that app in Azure.

  1. 在 Visual Studio Code 中选择 F1 键,打开命令面板。In Visual Studio Code, select F1 to open the command palette. 在命令面板中,搜索并选择“Azure Functions: 部署到函数应用”。In the command palette, search for and select Azure Functions: Deploy to function app.

  2. 如果尚未登录,系统会提示“登录到 Azure”。If you're not signed in, you're prompted to Sign in to Azure. 从浏览器登录后,请返回到 Visual Studio Code。After you sign in from the browser, go back to Visual Studio Code. 如果拥有多个订阅,请选择包含函数应用的订阅。If you have multiple subscriptions, Select a subscription that contains your function app.

  3. 在 Azure 中选择现有的函数应用。Select your existing function app in Azure. 收到有关覆盖函数应用中的所有文件的警告时,请选择“部署”以确认警告并继续。When you're warned about overwriting all files in the function app, select Deploy to acknowledge the warning and continue.

项目将重新构建、重新打包并上传到 Azure。The project is rebuilt, repackaged, and uploaded to Azure. 现有项目将替换为新包,且函数应用将重启。The existing project is replaced by the new package, and the function app restarts.

获取已部署的函数的 URLGet the URL of the deployed function

为了能够调用 HTTP 触发的函数,需要获取函数在部署到函数应用时的 URL。To call an HTTP-triggered function, you need the URL of the function when it's deployed to your function app. 此 URL 包含全部所需的函数密钥This URL includes any required function keys. 可以使用扩展获取已部署的函数的这些 URL。You can use the extension to get these URLs for your deployed functions.

  1. 按 F1 打开命令面板,然后搜索并运行命令“Azure Functions:Copy Function URLSelect F1 to open the command palette, and then search for and run the command Azure Functions: Copy Function URL.

  2. 按提示选择 Azure 中的函数应用,然后选择要调用的特定 HTTP 触发器。Follow the prompts to select your function app in Azure and then the specific HTTP trigger that you want to invoke.

函数 URL 将复制到剪贴板,同时,将使用 code 查询参数传递全部所需的密钥。The function URL is copied to the clipboard, along with any required keys passed by the code query parameter. 使用 HTTP 工具提交 POST 请求,或使用浏览器对远程函数发出 GET 请求。Use an HTTP tool to submit POST requests, or a browser for GET requests to the remote function.

在本地运行函数Run functions locally

Azure Functions 扩展可让你在本地开发计算机上运行函数项目。The Azure Functions extension lets you run a Functions project on your local development computer. 本地运行时是在 Azure 中托管函数应用的同一个运行时。The local runtime is the same runtime that hosts your function app in Azure. 将从 local.settings.json 文件读取本地设置。Local settings are read from the local.settings.json file.

在本地运行项目的其他要求Additional requirements for running a project locally

若要在本地运行函数项目,必须满足以下附加要求:To run your Functions project locally, you must meet these additional requirements:

将项目配置为在本地运行Configure the project to run locally

对于除 HTTP 和 Webhook 以外的所有触发器类型,Functions 运行时在内部使用 Azure 存储帐户。The Functions runtime uses an Azure Storage account internally for all trigger types other than HTTP and webhooks. 因此,需要将 Values.AzureWebJobsStorage 键设置为有效的 Azure 存储帐户连接字符串。So you need to set the Values.AzureWebJobsStorage key to a valid Azure Storage account connection string.

本部分结合使用 Visual Studio Code 的 Azure 存储扩展Azure 存储资源管理器进行连接并检索存储连接字符串。This section uses the Azure Storage extension for Visual Studio Code with Azure Storage Explorer to connect to and retrieve the storage connection string.

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

  1. 在 Visual Studio 中,打开“Cloud Explorer”,展开“存储帐户” > “你的存储帐户”,然后选择“属性面板”并复制“主连接字符串”值。 In Visual Studio, open Cloud Explorer, expand Storage Account > Your Storage Account, and 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.

有关详细信息,请参阅本地设置文件For more information, see Local settings file.

在本地调试函数Debugging functions locally

若要调试函数,请按 F5。To debug your functions, select F5. 如果你尚未下载 Core Tools,系统会提示你下载。If you haven't already downloaded Core Tools, you're prompted to do so. 安装后运行 Core Tools 时,输出将显示在终端中。When Core Tools is installed and running, output is shown in the Terminal. 这与从终端运行 func host start Core Tools 命令的结果相同,不过,此处使用了其他生成任务和附加的调试器。This is the same as running the func host start Core Tools command from the Terminal, but with additional build tasks and an attached debugger.

当项目正在运行时,可以像将项目部署到 Azure 时一样触发函数。When the project is running, you can trigger your functions as you would when the project is deployed to Azure. 在调试模式下运行项目时,将按预期命中 Visual Studio Code 中的断点。When the project is running in debug mode, breakpoints are hit in Visual Studio Code, as expected.

HTTP 触发器的请求 URL 显示在终端输出中。The request URL for HTTP triggers is displayed in the output in the Terminal. 在本地运行项目时,不会使用 HTTP 触发器的函数密钥。Function keys for HTTP triggers aren't used when a project is running locally. 有关详细信息,请参阅在 Azure Functions 中测试代码的策略For more information, see Strategies for testing your code in Azure Functions.

有关详细信息,请参阅使用 Azure Functions Core ToolsTo learn more, see Work with Azure Functions Core Tools.

本地设置文件Local settings file

local.settings.json 文件存储应用设置、连接字符串和本地开发工具使用的设置。The local.settings.json file stores app settings, connection strings, and settings used by local development tools. 只有在本地运行项目时,才会使用 local.settings.json 文件中的设置。Settings in the local.settings.json file are used only when you're running projects locally. 本地设置文件的结构如下:The local settings file has this structure:

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "<language worker>",
    "AzureWebJobsStorage": "<connection-string>",
    "AzureWebJobsDashboard": "<connection-string>",
    "MyBindingConnection": "<binding-connection-string>"
  },
  "Host": {
    "LocalHttpPort": 7071,
    "CORS": "*",
    "CORSCredentials": false
  },
  "ConnectionStrings": {
    "SQLConnectionString": "<sqlclient-connection-string>"
  }
}

在本地运行项目时,支持这些设置:These settings are supported when you run projects locally:

设置Setting 说明Description
IsEncrypted 当此设置设为 true 时,所有值都使用本地计算机密钥进行加密。When this setting is set to true, all values are encrypted with a local machine key. func settings 命令配合使用。Used with func settings commands. 默认值为 falseDefault value is false.
Values 在本地运行项目时使用的应用程序设置和连接字符串的数组。Array of application settings and connection strings used when a project is running locally. 这些键值 (string-string) 对与 Azure 的函数应用中的应用程序设置相对应,例如 AzureWebJobsStorageThese key-value (string-string) pairs correspond to application settings in your function app in Azure, like AzureWebJobsStorage. 许多触发器和绑定都有一个引用连接字符串应用设置的属性,例如 Blob 存储触发器ConnectionMany triggers and bindings have a property that refers to a connection string app setting, like Connection for the Blob storage trigger. 对于此类属性,你需要一个在 Values 数组中定义的应用程序设置。For these properties, you need an application setting defined in the Values array.
对于 HTTP 之外的触发器,AzureWebJobsStorage 是一个必需的应用设置。AzureWebJobsStorage is a required app setting for triggers other than HTTP.
2.x 版及更高版本的 Functions 运行时需要 [FUNCTIONS_WORKER_RUNTIME] 设置,该设置是由 Core Tools 为项目生成的。Version 2.x and higher of the Functions runtime requires the [FUNCTIONS_WORKER_RUNTIME] setting, which is generated for your project by Core Tools.
在本地安装 Azure 存储模拟器后,可以将 AzureWebJobsStorage 设置为 UseDevelopmentStorage=true,以便 Core Tools 使用此模拟器。When you have the Azure storage emulator installed locally and you set AzureWebJobsStorage to UseDevelopmentStorage=true, Core Tools uses the emulator. 此模拟器在开发期间非常有用,但是在部署之前,应当使用实际的存储连接进行测试。The emulator is useful during development, but you should test with an actual storage connection before deployment.
值必须是字符串,而不能是 JSON 对象或数组。Values must be strings and not JSON objects or arrays. 设置名称不能包含冒号 (:) 或双下划线 (__)。Setting names can't include a colon (:) or a double underline (__). 这些字符由运行时保留。These characters are reserved by the runtime.
Host 在本地运行项目时,本部分中的设置会自定义 Functions 主机进程。Settings in this section customize the Functions host process when you run projects locally. 这些设置独立于 host json 设置,后者在 Azure 中运行项目时也适用。These settings are separate from the host.json settings, which also apply when you run projects in Azure.
LocalHttpPort 设置运行本地 Functions 主机时使用的默认端口(func host startfunc run)。Sets the default port used when running the local Functions host (func host start and func run). --port 命令行选项优先于此设置。The --port command-line option takes precedence over this setting.
CORS 定义跨域资源共享 (CORS)可以使用的来源。Defines the origins allowed for cross-origin resource sharing (CORS). 以逗号分隔的列表提供来源,其中不含空格。Origins are supplied as a comma-separated list with no spaces. 支持通配符值 (*),它允许使用任何来源的请求。The wildcard value (*) is supported, which allows requests from any origin.
CORSCredentials 设置为 true 时,允许 withCredentials 请求。When set to true, allows withCredentials requests.
ConnectionStrings 一个集合。A collection. 不要将此集合用于函数绑定使用的连接字符串。Don't use this collection for the connection strings used by your function bindings. 此集合仅供通常从配置文件的 ConnectionStrings 节获取连接字符串的框架使用,例如实体框架This collection is used only by frameworks that typically get connection strings from the ConnectionStrings section of a configuration file, like Entity Framework. 此对象中的连接字符串添加到提供者类型为 System.Data.SqlClient 的环境中。Connection strings in this object are added to the environment with the provider type of System.Data.SqlClient. 此集合中的项不会使用其他应用设置发布到 Azure。Items in this collection aren't published to Azure with other app settings. 必须将这些值显式添加到函数应用设置的 Connection strings 集合中。You must explicitly add these values to the Connection strings collection of your function app settings. 如果要在函数代码中创建 SqlConnection,则应将连接字符串值与其他连接一起存储在门户的应用程序设置中。If you're creating a SqlConnection in your function code, you should store the connection string value with your other connections in Application Settings in the portal.

默认情况下,将项目发布到 Azure 时,这些设置不会自动迁移。By default, these settings aren't migrated automatically when the project is published to Azure. 发布完成后,系统会提供将 local.settings.json 中的设置发布到 Azure 中的函数应用的选项。After publishing finishes, you're given the option of publishing settings from local.settings.json to your function app in Azure. 有关详细信息,请参阅发布应用程序设置To learn more, see Publish application settings.

ConnectionStrings 中的值永远不会发布。Values in ConnectionStrings are never published.

还可以在代码中读取环境变量形式的函数应用程序设置值。The function application settings values can also be read in your code as environment variables. 有关详细信息,请参阅以下特定于语言的参考文章的“环境变量”部分:For more information, see the Environment variables sections of these language-specific reference articles:

Azure 中的应用程序设置Application settings in Azure

项目中 local.settings.json 文件内的设置应与 Azure 中函数应用内的应用程序设置相同。The settings in the local.settings.json file in your project should be the same as the application settings in the function app in Azure. 还必须将在 local.settings.json 中添加的任何设置添加到 Azure 函数应用中。Any settings you add to local.settings.json must also be added to the function app in Azure. 发布项目时,不会自动上传这些设置。These settings aren't uploaded automatically when you publish the project. 同样,通过门户在函数应用中创建的任何设置必须下载到本地项目。Likewise, any settings that you create in your function app in the portal must be downloaded to your local project.

发布应用程序设置Publish application settings

将所需设置发布到 Azure 中的函数应用的最简单方法是使用成功发布项目之后显示的“上传设置”链接。The easiest way to publish the required settings to your function app in Azure is to use the Upload settings link that appears after you publish your project:

上传应用程序设置

也可以使用命令面板中的“Azure Functions:上传本地设置”命令来发布设置。You can also publish settings by using the Azure Functions: Upload Local Setting command in the command palette. 可以使用“Azure Functions:添加新设置”命令将各个设置添加到 Azure 中的应用程序设置。You can add individual settings to application settings in Azure by using the Azure Functions: Add New Setting command.

提示

在发布 local.settings.json 文件之前,请务必保存它。Be sure to save your local.settings.json file before you publish it.

如果本地文件已加密,则会将其解密、发布,然后再次加密。If the local file is encrypted, it's decrypted, published, and encrypted again. 如果两个位置中的设置使用了有冲突的值,系统会提示你选择如何继续。If there are settings that have conflicting values in the two locations, you're prompted to choose how to proceed.

在“Azure: Functions”区域中,依次展开你的订阅、函数应用和“应用程序设置”,查看现有的应用设置。View existing app settings in the Azure: Functions area by expanding your subscription, your function app, and Application Settings.

在 Visual Studio Code 中查看函数应用设置

从 Azure 下载设置Download settings from Azure

如果已在 Azure 中创建应用程序设置,可以使用“Azure Functions:下载远程设置”命令将其下载到 local.settings.json 文件中。If you've created application settings in Azure, you can download them into your local.settings.json file by using the Azure Functions: Download Remote Settings command.

与上传时一样,如果本地文件已加密,则会将其解密、更新,然后再次加密。As with uploading, if the local file is encrypted, it's decrypted, updated, and encrypted again. 如果两个位置中的设置使用了有冲突的值,系统会提示你选择如何继续。If there are settings that have conflicting values in the two locations, you're prompted to choose how to proceed.

监视函数Monitoring functions

本地运行函数时,日志数据将流式传输到终端控制台。When you run functions locally, log data is streamed to the Terminal console. 当 Functions 项目在 Azure 中的函数应用内运行时,也可以获取日志数据。You can also get log data when your Functions project is running in a function app in Azure. 可以连接到 Azure 中的流日志,以查看近实时的日志数据。You can either connect to streaming logs in Azure to see near-real-time log data.

流式处理日志Streaming logs

开发应用程序时,以近乎实时的方式查看日志记录信息通常很有用。When you're developing an application, it's often useful to see logging information in near-real time. 可以查看函数正在生成的日志文件流。You can view a stream of log files being generated by your functions. 以下输出是对 HTTP 触发的函数发出请求后生成的流日志示例:This output is an example of streaming logs for a request to an HTTP-triggered function:

HTTP 触发器的流日志输出

若要在 Azure 中为函数应用启用流式处理日志,请执行以下操作:To turn on the streaming logs for your function app in Azure:

  1. 选择 F1 打开命令面板,然后搜索并运行命令“Azure Functions: 开始流式处理日志”。Select F1 to open the command palette, and then search for and run the command Azure Functions: Start Streaming Logs.

  2. 在 Azure 中选择函数应用,然后选择“是” 为函数应用启用应用程序日志记录。Select your function app in Azure, and then select Yes to enable application logging for the function app.

  3. 在 Azure 中触发函数。Trigger your functions in Azure. 请注意,日志数据显示在 Visual Studio Code 的“输出”窗口中。Notice that log data is displayed in the Output window in Visual Studio Code.

  4. 完成后,请记得运行命令“Azure Functions: 停止流式处理日志”为函数应用禁用日志记录。When you're done, remember to run the command Azure Functions: Stop Streaming Logs to disable logging for the function app.

备注

流日志仅支持单个 Functions 宿主实例。Streaming logs support only a single instance of the Functions host. 将函数扩展为多个实例时,不会在日志流中显示来自其他实例的数据。When your function is scaled to multiple instances, data from other instances isn't shown in the log stream.

C# 脚本项目C# script projects

默认情况下,所有 C# 项目创建为 C# 编译的类库项目By default, all C# projects are created as C# compiled class library projects. 如果你偏好使用 C# 脚本项目,则必须在 Azure Functions 扩展设置中选择 C# 脚本作为默认语言。If you prefer to work with C# script projects instead, you must select C# script as the default language in the Azure Functions extension settings:

  1. 选择“文件” > “首选项” > “设置”。 Select File > Preferences > Settings.

  2. 转到“用户设置” > “扩展” > “Azure Functions”。 Go to User Settings > Extensions > Azure Functions.

  3. 选择“C#Script”:“Azure Functions: 选择“C# 脚本”。Select C#Script from Azure Function: Project Language.

完成这些步骤后,对底层 Core Tools 发出的调用包含 --csx 选项,该选项会生成并发布 C# 脚本 (.csx) 项目文件。After you complete these steps, calls made to the underlying Core Tools include the --csx option, which generates and publishes C# script (.csx) project files. 如果指定了此默认语言,创建的所有项目将默认为 C# 脚本项目。When you have this default language specified, all projects that you create default to C# script projects. 如果设置了默认值,则系统不会提示你选择项目语言。You're not prompted to choose a project language when a default is set. 若要以其他语言创建项目,必须更改此设置,或者将其从用户的 settings.json 文件中删除。To create projects in other languages, you must change this setting or remove it from the user settings.json file. 删除此设置后,在创建项目时,系统会再次提示你选择语言。After you remove this setting, you're again prompted to choose your language when you create a project.

命令面板参考Command palette reference

Azure Functions 扩展在区域提供一个有用的图形界面,用于与 Azure 中的函数应用交互。The Azure Functions extension provides a useful graphical interface in the area for interacting with your function apps in Azure. 命令面板 (F1) 中的命令也具有相同的功能。The same functionality is also available as commands in the command palette (F1). 以下 Azure Functions 命令可用:These Azure Functions commands are available:

Azure Functions 命令Azure Functions command 说明Description
添加新设置Add New Settings 在 Azure 中创建新的应用程序设置。Creates a new application setting in Azure. 有关详细信息,请参阅发布应用程序设置To learn more, see Publish application settings. 可能还需要将此设置下载到本地设置You might also need to download this setting to your local settings.
配置部署源Configure Deployment Source 将 Azure 中的函数应用连接到本地 Git 存储库。Connects your function app in Azure to a local Git repository.
连接到 GitHub 存储库Connect to GitHub Repository 将函数应用连接到 GitHub 存储库。Connects your function app to a GitHub repository.
复制函数 URLCopy Function URL 获取 Azure 中运行的 HTTP 触发函数的远程 URL。Gets the remote URL of an HTTP-triggered function that's running in Azure. 有关详细信息,请参阅获取已部署的函数的 URLTo learn more, see Get the URL of the deployed function.
在 Azure 中创建函数应用Create function app in Azure 在 Azure 中的订阅内创建新的函数应用。Creates a new function app in your subscription in Azure. 有关详细信息,请参阅有关如何发布到 Azure 中的新函数应用的部分。To learn more, see the section on how to publish to a new function app in Azure.
解密设置Decrypt Settings 解密已由以下命令加密的本地设置:“Azure Functions:加密设置”。Decrypts local settings that have been encrypted by Azure Functions: Encrypt Settings.
删除函数应用Delete Function App 从 Azure 中的订阅内删除函数应用。Removes a function app from your subscription in Azure. 如果应用服务计划中没有其他应用,则系统也会提供用于删除其他应用的选项。When there are no other apps in the App Service plan, you're given the option to delete that too. 不会删除其他资源,例如存储帐户和资源组。Other resources, like storage accounts and resource groups, aren't deleted. 若要删除所有资源,应删除资源组To remove all resources, you should instead delete the resource group. 本地项目不受影响。Your local project isn't affected.
删除函数Delete Function 从 Azure 中的函数应用内删除现有的函数。Removes an existing function from a function app in Azure. 由于此删除操作不会影响本地项目,因此请考虑在本地删除函数,然后重新发布项目Because this deletion doesn't affect your local project, instead consider removing the function locally and then republishing your project.
删除代理Delete Proxy 从 Azure 中的函数应用内删除 Azure Functions 代理。Removes an Azure Functions proxy from your function app in Azure. 有关代理的详细信息,请参阅使用 Azure Functions 代理To learn more about proxies, see Work with Azure Functions Proxies.
删除设置Delete Setting 删除 Azure 中的函数应用设置。Deletes a function app setting in Azure. 此操作不影响 local.settings.json 文件中的设置。This deletion doesn't affect settings in your local.settings.json file.
从存储库断开连接Disconnect from Repo 删除 Azure 中的函数应用与源代码管理存储库之间的连续部署连接。Removes the continuous deployment connection between a function app in Azure and a source control repository.
下载远程设置Download Remote Settings 将 Azure 中所选函数应用的设置下载到 local.settings.json 文件中。Downloads settings from the chosen function app in Azure into your local.settings.json file. 如果本地文件已加密,则会将其解密、更新,然后再次加密。If the local file is encrypted, it's decrypted, updated, and encrypted again. 如果两个位置中的设置使用了有冲突的值,系统会提示你选择如何继续。If there are settings that have conflicting values in the two locations, you're prompted to choose how to proceed. 在运行此命令之前,请确保已保存对 local.settings.json 文件所做的更改。Be sure to save changes to your local.settings.json file before you run this command.
编辑设置Edit settings 更改 Azure 中现有函数应用设置的值。Changes the value of an existing function app setting in Azure. 此命令不影响 local.settings.json 文件中的设置。This command doesn't affect settings in your local.settings.json file.
加密设置Encrypt settings 加密本地设置Values 数组内的单个项。Encrypts individual items in the Values array in the local settings. 在此文件中,IsEncrypted 也设置为 true,指定本地运行时在使用设置之前先将其解密。In this file, IsEncrypted is also set to true, which specifies that the local runtime will decrypt settings before using them. 加密本地设置可以减少泄露重要信息的风险。Encrypt local settings to reduce the risk of leaking valuable information. 在 Azure 中,应用程序设置始终以加密的形式进行存储。In Azure, application settings are always stored encrypted.
立即执行函数Execute Function Now 在 Azure 中手动启动计时器触发的函数Manually starts a timer-triggered function in Azure. 此命令用于测试。This command is used for testing. 有关在 Azure 中触发非 HTTP 函数的详细信息,请参阅手动运行非 HTTP 触发的函数To learn more about triggering non-HTTP functions in Azure, see Manually run a non HTTP-triggered function.
初始化项目以便与 VS Code 配合使用Initialize Project for Use with VS Code 将所需的 Visual Studio Code 项目文件添加到现有的 Functions 项目。Adds the required Visual Studio Code project files to an existing Functions project. 运行此命令可以使用 Core Tools 处理创建的项目。Use this command to work with a project that you created by using Core Tools.
安装或更新 Azure Functions Core ToolsInstall or Update Azure Functions Core Tools 安装或更新用于在本地运行函数的 Azure Functions Core ToolsInstalls or updates Azure Functions Core Tools, which is used to run functions locally.
重新部署Redeploy 用于将项目文件从连接的 Git 存储库重新部署到 Azure 中的特定部署。Lets you redeploy project files from a connected Git repository to a specific deployment in Azure. 若要从 Visual Studio Code 重新发布本地更新,请重新发布项目To republish local updates from Visual Studio Code, republish your project.
重命名设置Rename Settings 更改 Azure 中现有函数应用设置的键名。Changes the key name of an existing function app setting in Azure. 此命令不影响 local.settings.json 文件中的设置。This command doesn't affect settings in your local.settings.json file. 重命名 Azure 中的设置后,应将这些更改下载到本地项目After you rename settings in Azure, you should download those changes to the local project.
重启Restart 重启 Azure 中的函数应用。Restarts the function app in Azure. 部署更新也会重启函数应用。Deploying updates also restarts the function app.
设置 AzureWebJobsStorageSet AzureWebJobsStorage 设置 AzureWebJobsStorage 应用程序设置的值。Sets the value of the AzureWebJobsStorage application setting. Azure Functions 需要此设置。This setting is required by Azure Functions. 此设置是在 Azure 中创建函数应用时指定的。It's set when a function app is created in Azure.
启动Start 启动 Azure 中已停止的函数应用。Starts a stopped function app in Azure.
启动流日志Start Streaming Logs 启动 Azure 中函数应用的流日志。Starts the streaming logs for the function app in Azure. 在 Azure 中进行远程故障排除期间,如果需要近实时查看日志信息,可以使用流日志。Use streaming logs during remote troubleshooting in Azure if you need to see logging information in near-real time. 有关详细信息,请参阅流日志To learn more, see Streaming logs.
停止Stop 停止 Azure 中运行的函数应用。Stops a function app that's running in Azure.
停止流日志Stop Streaming Logs 停止 Azure 中函数应用的流日志。Stops the streaming logs for the function app in Azure.
切换为槽设置Toggle as Slot Setting 启用后,请确保保留给定部署槽的应用程序设置。When enabled, ensures that an application setting persists for a given deployment slot.
卸载 Azure Functions Core ToolsUninstall Azure Functions Core Tools 删除扩展所需的 Azure Functions Core Tools。Removes Azure Functions Core Tools, which is required by the extension.
上传本地设置Upload Local Settings 将 local.settings.json 文件中的设置上传到 Azure 中所选的函数应用。Uploads settings from your local.settings.json file to the chosen function app in Azure. 如果本地文件已加密,则会将其解密、上传,然后再次加密。If the local file is encrypted, it's decrypted, uploaded, and encrypted again. 如果两个位置中的设置使用了有冲突的值,系统会提示你选择如何继续。If there are settings that have conflicting values in the two locations, you're prompted to choose how to proceed. 在运行此命令之前,请确保已保存对 local.settings.json 文件所做的更改。Be sure to save changes to your local.settings.json file before you run this command.
在 GitHub 中查看提交内容View Commit in GitHub 在函数应用已连接到存储库后,显示特定部署中的最新提交内容。Shows you the latest commit in a specific deployment when your function app is connected to a repository.
查看部署日志View Deployment Logs 显示 Azure 中函数应用的特定部署的日志。Shows you the logs for a specific deployment to the function app in Azure.

后续步骤Next steps

有关 Azure Functions Core Tools 的详细信息,请参阅使用 Azure Functions Core ToolsTo learn more about Azure Functions Core Tools, see Work with Azure Functions Core Tools.

若要了解有关以 .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 provides links to examples of how to use attributes to declare the various types of bindings supported by Azure Functions.