使用 Azure Functions Core ToolsWork with Azure Functions Core Tools

使用 Azure Functions Core Tools 可以在本地计算机上通过命令提示符或终端开发和测试函数。Azure Functions Core Tools lets you develop and test your functions on your local computer from the command prompt or terminal. 本地函数可以连接到实时 Azure 服务,你可以在本地计算机上使用完整的 Functions 运行时调试函数。Your local functions can connect to live Azure services, and you can debug your functions on your local computer using the full Functions runtime. 甚至可以将函数应用部署到 Azure 订阅。You can even deploy a function app to your Azure subscription.

Important

不要将本地开发和门户开发混合在同一函数应用中。Do not mix local development with portal development in the same function app. 从本地项目创建和发布函数时,不应尝试维护或修改门户中的项目代码。When you create and publish functions from a local project, you should not try to maintain or modify project code in the portal.

Core Tools 版本Core Tools versions

Azure Functions Core Tools 有两个版本。There are two versions of Azure Functions Core Tools. 使用的版本取决于本地开发环境、所选的语言以及所需的支持级别:The version you use depends on your local development environment, choice of language, and level of support required:

除非另有说明,否则本文中的示例适用于版本 2.x。Unless otherwise noted, the examples in this article are for version 2.x.

安装 Azure Functions Core ToolsInstall the Azure Functions Core Tools

Azure Functions Core Tools 包含同一运行时的另一版本,该版本为本地开发计算机上可运行的 Azure Functions 运行时提供支持。Azure Functions Core Tools includes a version of the same runtime that powers Azure Functions runtime that you can run on your local development computer. 它还提供用于创建函数、连接到 Azure 和部署函数项目的命令。It also provides commands to create functions, connect to Azure, and deploy function projects.

2.x 版Version 2.x

2.x 版工具使用构建在 .NET Core 之上的 Azure Functions 运行时 2.x。Version 2.x of the tools uses the Azure Functions runtime 2.x that is built on .NET Core. .NET Core 2.x 支持的所有平台(包括 WindowsmacOSLinux)都支持此版本。This version is supported on all platforms .NET Core 2.x supports, including Windows, macOS, and Linux. 必须先安装 .NET Core 2.x SDK。You must first install the .NET Core 2.x SDK.

WindowsWindows

以下步骤使用 npm 在 Windows 上安装 Core Tools。The following steps use npm to install Core Tools on Windows. 也可使用 ChocolateyYou can also use Chocolatey. 有关详细信息,请参阅 Core Tools 自述文件For more information, see the Core Tools readme.

  1. 安装用于 Windows 的 .NET Core 2.x SDKInstall .NET Core 2.x SDK for Windows.

  2. 安装 Node.js,其中包括 npm。Install Node.js, which includes npm. 对于 2.x 版工具,仅支持 Node.js 8.5 和更高版本。For version 2.x of the tools, only Node.js 8.5 and later versions are supported.

  3. 安装 Core Tools 包:Install the Core Tools package:

    npm install -g azure-functions-core-tools
    

带 Homebrew 的 MacOSMacOS with Homebrew

以下步骤使用 Homebrew 在 macOS 上安装 Core Tools。The following steps use Homebrew to install the Core Tools on macOS.

  1. 安装用于 macOS 的 .NET Core 2.x SDKInstall .NET Core 2.x SDK for macOS.

  2. 安装 Homebrew(如果尚未安装)。Install Homebrew, if it's not already installed.

  3. 安装 Core Tools 包:Install the Core Tools package:

    brew tap azure/functions
    brew install azure-functions-core-tools
    

带 APT 的 Linux (Ubuntu/Debian)Linux (Ubuntu/Debian) with APT

以下步骤使用 APT 在 Ubuntu/Debian Linux 发行版上安装 Core Tools。The following steps use APT to install Core Tools on your Ubuntu/Debian Linux distribution. 有关其他 Linux 发行版,请参阅 Core Tools 自述文件For other Linux distributions, see the Core Tools readme.

  1. 安装用于 Linux 的 .NET Core 2.x SDKInstall .NET Core 2.x SDK for Linux.

  2. 将 Microsoft 产品密钥注册为受信任的密钥:Register the Microsoft product key as trusted:

    curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
    sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg
    
  3. 验证你的 Ubuntu 服务器正在运行下表中的合适版本之一。Verify your Ubuntu server is running one of the appropriate versions from the table below. 若要添加 apt 源,请运行:To add the apt source, run:

    sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-$(lsb_release -cs)-prod $(lsb_release -cs) main" > /etc/apt/sources.list.d/dotnetdev.list'
    sudo apt-get update
    
    Linux 分发版Linux distribution 版本Version
    Ubuntu 18.10Ubuntu 18.10 cosmic
    Ubuntu 18.04Ubuntu 18.04 bionic
    Ubuntu 17.04Ubuntu 17.04 zesty
    Ubuntu 16.04/Linux Mint 18Ubuntu 16.04/Linux Mint 18 xenial
  4. 安装 Core Tools 包:Install the Core Tools package:

    sudo apt-get install azure-functions-core-tools
    

创建本地 Functions 项目Create a local Functions project

Functions 项目目录包含文件 host.jsonlocal.settings.json 以及若干个子文件夹,这些子文件夹包含各个函数的代码。A functions project directory contains the files host.json and local.settings.json, along with subfolders that contain the code for individual functions. 此目录相当于 Azure 中的一个函数应用。This directory is the equivalent of a function app in Azure. 若要详细了解 Functions 文件夹的结构,请参阅 Azure Functions 开发人员指南To learn more about the Functions folder structure, see the Azure Functions developers guide.

版本 2.x 要求在初始化项目时为项目选择默认语言,添加的所有函数使用默认语言模板。Version 2.x requires you to select a default language for your project when it is initialized, and all functions added use default language templates. 在版本 1.x 中,每次创建函数时都要指定语言。In version 1.x, you specify the language each time you create a function.

在终端窗口中或者在命令提示符下,运行以下命令创建项目和本地 Git 存储库:In the terminal window or from a command prompt, run the following command to create the project and local Git repository:

func init MyFunctionProj

提供项目名称后,系统就会创建并初始化使用该名称的新文件夹,When you provide a project name, a new folder with that name is created and initialized. 否则会初始化当前文件夹。Otherwise, the current folder is initialized.
在版本 2.x 中运行命令时,必须为项目选择一个运行时。In version 2.x, when you run the command you must choose a runtime for your project. 如果你打算开发 JavaScript 函数,请选择“节点”:If you plan to develop JavaScript functions, choose node:

Select a worker runtime:
dotnet
node

使用向上/向下箭头键选择语言,然后按 Enter。Use the up/down arrow keys to choose a language, then press Enter. JavaScript 项目的输出如以下示例所示:The output looks like the following example for a JavaScript project:

Select a worker runtime: node
Writing .gitignore
Writing host.json
Writing local.settings.json
Writing C:\myfunctions\myMyFunctionProj\.vscode\extensions.json
Initialized empty Git repository in C:/myfunctions/myMyFunctionProj/.git/

func init 支持以下选项。除非另有说明,否则这些选项仅限版本 2.x:func init supports the following options, which are version 2.x-only, unless otherwise noted:

选项Option 说明Description
--csx 初始化 C# 脚本 (.csx) 项目。Initializes a C# script (.csx) project. 必须在后续命令中指定 --csxYou must specify --csx in subsequent commands.
--docker 使用基于所选 --worker-runtime 的基础映像创建容器的 Dockerfile。Create a Dockerfile for a container using a base image that is based on the chosen --worker-runtime. 如果打算发布到自定义 Linux 容器,请使用此选项。Use this option when you plan to publish to a custom Linux container.
--force 即使项目中存在现有的文件,也要初始化该项目。Initialize the project even when there are existing files in the project. 此设置会覆盖同名的现有文件。This setting overwrites existing files with the same name. 项目文件夹中的其他文件不受影响。Other files in the project folder aren't affected.
--no-source-control -n 阻止版本 1.x 中默认创建 Git 存储库的行为。Prevents the default creation of a Git repository in version 1.x. 在版本 2.x 中,默认不会创建 git 存储库。In version 2.x, the git repository isn't created by default.
--source-control 控制是否创建 git 存储库。Controls whether a git repository is created. 默认不会创建存储库。By default, a repository isn't created. 如果为 true,则会创建存储库。When true, a repository is created.
--worker-runtime 设置项目的语言运行时。Sets the language runtime for the project. 支持的值为 dotnetnode (JavaScript)、javapythonSupported values are dotnet, node (JavaScript), java, and python. 如果未设置,则初始化期间系统会提示你选择运行时。When not set, you are prompted to choose your runtime during initialization.

Important

默认情况下,Core Tools 版本 2.x 会为 .NET 运行时创建函数应用项目作为 C# 类项目 (.csproj)。By default, version 2.x of the Core Tools creates function app projects for the .NET runtime as C# class projects (.csproj). 这些 C# 项目可以与 Visual Studio 或 Visual Studio Code 结合使用,在测试期间以及发布到 Azure 时进行编译。These C# projects, which can be used with Visual Studio or Visual Studio Code, are compiled during testing and when publishing to Azure. 如果希望创建并使用在版本 1.x 和门户中创建的相同 C# 脚本 (.csx) 文件,则在创建和部署函数时必须包含 --csx 参数。If you instead want to create and work with the same C# script (.csx) files created in version 1.x and in the portal, you must include the --csx parameter when you create and deploy functions.

注册扩展Register extensions

在版本 2.x 的 Azure Functions 运行时中,必须显式注册在函数应用中使用的绑定扩展(绑定类型)。In version 2.x of the Azure Functions runtime, you have to explicitly register the binding extensions (binding types) that you use in your function app.

在本地开发函数时,可以使用 Azure Functions Core Tools 从终端或从命令提示符安装所需的扩展。When you develop functions locally, you can install the extensions you need by using the Azure Functions Core Tools from the Terminal or from a command prompt.

更新 function.json 文件以包含函数所需的所有绑定后,请在项目文件夹中运行以下命令。After you have updated your function.json file to include all the bindings that your function needs, run the following command in the project folder.

func extensions install

该命令读取 function.json 文件以了解所需的程序包,安装这些包并重新生成扩展项目。The command reads the function.json file to see which packages you need, installs them, and rebuilds the extensions project. 它在当前版本中添加任何新绑定,但不更新现有绑定。It adds any new bindings at the current version but does not update existing bindings. 使用 --force 选项可在安装新版本时将现有绑定更新为最新版本。Use the --force option to update existing bindings to the latest version when installing new ones.

如要安装特定版本的包或要在编辑 function.json 文件之前安装包,请对包名称使用 func extensions install 命令,如下例所示:If you want to install a particular version of a package or you want to install packages before editing the function.json file, use the func extensions install command with the name of the package, as shown in the following example:

func extensions install --package Microsoft.Azure.WebJobs.ServiceBus --version <target_version>

<target_version> 替换为特定包版本,例如 3.0.0-beta5Replace <target_version> with a specific version of the package, such as 3.0.0-beta5. NuGet.org 上的单个包页上列出了有效版本。Valid versions are listed on the individual package pages at NuGet.org.

有关详细信息,请参阅 Azure Functions 触发器和绑定概念For more information, see Azure Functions triggers and bindings concepts.

本地设置文件Local settings file

文件 local.settings.json 存储 Azure Functions Core Tools 的应用设置、连接字符串和设置。The file local.settings.json stores app settings, connection strings, and settings for Azure Functions Core Tools. 只有在本地运行时,Functions工具才使用 local.settings.json 文件中的设置。Settings in the local.settings.json file are only used by Functions tools when running locally. 默认情况下,将项目发布到 Azure 时,这些设置不会自动迁移。By default, these settings are not migrated automatically when the project is published to Azure. 发布时使用 --publish-local-settings 开关确保已将这些设置添加到 Azure 中的函数应用。Use the --publish-local-settings switch when you publish to make sure these settings are added to the function app in Azure. 请注意,ConnectionStrings 中的值永远不会发布。Note that values in ConnectionStrings are never published. 该文件的结构如下:The file has the following structure:

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "<language worker>",
    "AzureWebJobsStorage": "<connection-string>",
    "AzureWebJobsDashboard": "<connection-string>",
    "MyBindingConnection": "<binding-connection-string>"
  },
  "Host": {
    "LocalHttpPort": 7071,
    "CORS": "*"
  },
  "ConnectionStrings": {
    "SQLConnectionString": "<sqlclient-connection-string>"
  }
}
设置Setting 说明Description
IsEncrypted 设置为 true 时,使用本地计算机密钥加密所有值。When set to true, all values are encrypted using a local machine key. func settings 命令配合使用。Used with func settings commands. 默认值为 falseDefault value is false.
Values 在本地运行时使用的应用程序设置和连接字符串的集合。Collection of application settings and connection strings used when running locally. 这些值对应于 Azure 中你的函数应用中的应用设置,例如 AzureWebJobsStorageThese values correspond to app settings in your function app in Azure, such as AzureWebJobsStorage. 许多触发器和绑定都有一个引用连接字符串应用设置的属性,例如 Blob 存储触发器ConnectionMany triggers and bindings have a property that refers to a connection string app setting, such as Connection for the Blob storage trigger. 对于此类属性,你需要一个在 Values 数组中定义的应用程序设置。For such 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 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, you can set AzureWebJobsStorage to UseDevelopmentStorage=true and Core Tools uses the emulator. 这在开发期间非常有用,但是在部署之前,应当使用实际的存储连接进行测试。This is useful during development, but you should test with an actual storage connection before deployment.
Host 在本地运行时,本部分中的设置会自定义 Functions 主机进程。Settings in this section customize the Functions host process when running locally.
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 value.
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.
ConnectionStrings 不要将此集合用于函数绑定使用的连接字符串。Do not use this collection for the connection strings used by your function bindings. 此集合仅供通常从配置文件的 ConnectionStrings 节获取连接字符串的框架使用,例如实体框架This collection is only used by frameworks that typically get connection strings from the ConnectionStrings section of a configuration file, such as 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 are not 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 are creating a SqlConnection in your function code, you should store the connection string value in Application Settings in the portal with your other connections.

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

如果没有为 AzureWebJobsStorage 设置有效的存储连接字符串并且没有使用模拟器,则会显示以下错误消息:When no valid storage connection string is set for AzureWebJobsStorage and the emulator isn't being used, the following error message is shown:

local.settings.json 中的 AzureWebJobsStorage 缺少值。Missing value for AzureWebJobsStorage in local.settings.json. 该值对除 HTTP 以外的所有触发器都是必需的。This is required for all triggers other than HTTP. 可运行“func azure functionapp fetch-app-settings <functionAppName>”或在 local.settings.json 中指定连接字符串。You can run 'func azure functionapp fetch-app-settings <functionAppName>' or specify a connection string in local.settings.json.

获取存储连接字符串Get your storage connection strings

即使在使用存储仿真器进行开发时,你也可能希望使用实际的存储连接进行测试。Even when using the storage emulator for development, you may want to test with an actual storage connection. 假设已创建了存储帐户,则可以通过下列方式之一获取有效的存储连接字符串:Assuming you have already created a storage account, you can get a valid storage connection string in one of the following ways:

  • 通过 Azure 门户From the Azure portal. 导航到你的存储帐户,在“设置”中选择“访问密钥”,然后复制其中一个连接字符串值。Navigate to your storage account, select Access keys in Settings, then copy one of the Connection string values.

    从 Azure 门户复制连接字符串

  • 使用 Azure 存储资源管理器连接到你的 Azure 帐户。Use Azure Storage Explorer to connect to your Azure account. 在“资源管理器”中,展开你的订阅,选择你的存储帐户,然后复制主或辅助连接字符串。In the Explorer, expand your subscription, select your storage account, and copy the primary or secondary connection string.

    从存储资源管理器复制连接字符串

  • 使用核心工具通过下列命令之一从 Azure 下载连接字符串:Use Core Tools to download the connection string from Azure with one of the following commands:

    • 从现有函数应用下载所有设置:Download all settings from an existing function app:

      func azure functionapp fetch-app-settings <FunctionAppName>
      
    • 获取特定存储帐户的连接字符串。Get the Connection string for a specific storage account:

      func azure storage fetch-connection-string <StorageAccountName>
      

      如果你尚未登录到 Azure,系统会要求登录。When you are not already signed in to Azure, you are prompted to do so.

创建函数Create a function

若要创建函数,请运行以下命令:To create a function, run the following command:

func new

在版本 2.x 中运行 func new 时,系统会提示你选择采用函数应用默认语言的模板,另外还会提示你选择函数的名称。In version 2.x, when you run func new you are prompted to choose a template in the default language of your function app, then you are also prompted to choose a name for your function. 在版本 1.x 中,系统还会提示你选择语言。In version 1.x, you are also prompted to choose the language.

Select a language: Select a template:
Blob trigger
Cosmos DB trigger
HTTP trigger
Queue trigger
SendGrid
Service Bus Queue trigger
Service Bus Topic trigger
Timer trigger

函数代码在具有所提供的函数名称的子文件夹中生成,如以下队列触发器输出中所示:Function code is generated in a subfolder with the provided function name, as you can see in the following queue trigger output:

Select a language: Select a template: Queue trigger
Function name: [QueueTriggerJS] MyQueueTrigger
Writing C:\myfunctions\myMyFunctionProj\MyQueueTrigger\index.js
Writing C:\myfunctions\myMyFunctionProj\MyQueueTrigger\readme.md
Writing C:\myfunctions\myMyFunctionProj\MyQueueTrigger\sample.dat
Writing C:\myfunctions\myMyFunctionProj\MyQueueTrigger\function.json

也可以在命令中使用以下参数指定这些选项:You can also specify these options in the command using the following arguments:

参数Argument 说明Description
--csx (版本 2.x)生成版本 1.x 和门户所用的相同 C# 脚本 (.csx) 模板。(Version 2.x) Generates the same C# script (.csx) templates used in version 1.x and in the portal.
--language -l C#、F# 或 JavaScript 等模板编程语言。The template programming language, such as C#, F#, or JavaScript. 此选项在版本 1.x 中是必需的。This option is required in version 1.x. 在版本 2.x 中,请不要使用此选项或选择与辅助角色运行时匹配的语言。In version 2.x, do not use this option or choose a language that matches the worker runtime.
--name -n 函数名称。The function name.
--template -t 使用 func templates list 命令查看每种受支持语言的可用模板的完整列表。Use the func templates list command to see the complete list of available templates for each supported language.

例如,若要在单个命令中创建 JavaScript HTTP 触发器,请运行:For example, to create a JavaScript HTTP trigger in a single command, run:

func new --template "Http Trigger" --name MyHttpTrigger

若要在单个命令中创建队列触发的函数,请运行:To create a queue-triggered function in a single command, run:

func new --template "Queue Trigger" --name QueueTriggerJS

在本地运行函数Run functions locally

若要运行 Functions 项目,请运行 Functions 主机。To run a Functions project, run the Functions host. 主机为项目中的所有函数启用触发器:The host enables triggers for all functions in the project:

func host start

host 命令仅在版本 1.x 中为必需命令。The host command is only required in version 1.x.

func host start 支持以下选项:func host start supports the following options:

选项Option 说明Description
--no-build 在运行之前请勿生成当前项目。Do no build current project before running. 仅限于 dotnet 项目。For dotnet projects only. 默认设置为 false。Default is set to false. 仅限 2.x 版。Version 2.x only.
--cert 包含私钥的 .pfx 文件的路径。The path to a .pfx file that contains a private key. 只能与 --useHttps 配合使用。Only used with --useHttps. 仅限 2.x 版。Version 2.x only.
--cors-credentials 允许跨域经身份验证的请求(例如 cookies 和身份验证标头),仅限版本 2.x。Allow cross-origin authenticated requests (i.e. cookies and the Authentication header) Version 2.x only.
--cors 以逗号分隔的 CORS 来源列表,其中不包含空格。A comma-separated list of CORS origins, with no spaces.
--language-worker 用于配置语言辅助角色的参数。Arguments to configure the language worker. 仅限 2.x 版。Version 2.x only.
--nodeDebugPort -n 节点调试程序要使用的端口。The port for the node debugger to use. 默认值:launch.json 中的值或 5858。Default: A value from launch.json or 5858. 仅限 1.x 版。Version 1.x only.
--password 密码或包含 .pfx 文件密码的文件。Either the password or a file that contains the password for a .pfx file. 只能与 --cert 配合使用。Only used with --cert. 仅限 2.x 版。Version 2.x only.
--port -p 要侦听的本地端口。The local port to listen on. 默认值:7071。Default value: 7071.
--pause-on-error 退出进程前,暂停增加其他输入。Pause for additional input before exiting the process. 仅当从集成开发环境 (IDE) 启动 Core Tools 时才使用。Used only when launching Core Tools from an integrated development environment (IDE).
--script-root --prefix 用于指定要运行或部署的函数应用的根目录路径。Used to specify the path to the root of the function app that is to be run or deployed. 此选项用于可在子文件夹中生成项目文件的已编译项目。This is used for compiled projects that generate project files into a subfolder. 例如,生成 C# 类库项目时,将在某个根子文件夹中生成 host.json、local.settings.json 和 function.json 文件,其路径类似于 MyProject/bin/Debug/netstandard2.0For example, when you build a C# class library project, the host.json, local.settings.json, and function.json files are generated in a root subfolder with a path like MyProject/bin/Debug/netstandard2.0. 在这种情况下,请将前缀设置为 --script-root MyProject/bin/Debug/netstandard2.0In this case, set the prefix as --script-root MyProject/bin/Debug/netstandard2.0. 这是在 Azure 中运行的函数应用的根目录。This is the root of the function app when running in Azure.
--timeout -t Functions 主机启动的超时时间(以秒为单位)。The timeout for the Functions host to start, in seconds. 默认值:20 秒。Default: 20 seconds.
--useHttps 绑定到 https://localhost:{port} ,而不是绑定到 http://localhost:{port}Bind to https://localhost:{port} rather than to http://localhost:{port}. 默认情况下,此选项会在计算机上创建可信证书。By default, this option creates a trusted certificate on your computer.

对于 C# 类库项目 (.csproj),必须包括 --build 选项才能生成库 .dll。For a C# class library project (.csproj), you must include the --build option to generate the library .dll.

Functions 主机启动时,会输出 HTTP 触发的函数的 URL:When the Functions host starts, it outputs the URL of HTTP-triggered functions:

Found the following functions:
Host.Functions.MyHttpTrigger

Job host started
Http Function MyHttpTrigger: http://localhost:7071/api/MyHttpTrigger

Important

在本地运行时,不会对 HTTP 终结点强制执行身份验证。When running locally, authentication isn't enforced for HTTP endpoints. 这意味着所有本地 HTTP 请求都将作为 authLevel = "anonymous" 处理。This means that all local HTTP requests are handled as authLevel = "anonymous". 有关详细信息,请参阅 HTTP 绑定一文。For more information, see the HTTP binding article.

将测试数据传递给函数Passing test data to a function

若要在本地测试函数,请启动 Functions 主机,并在本地服务器上使用 HTTP 请求调用终结点。To test your functions locally, you start the Functions host and call endpoints on the local server using HTTP requests. 你调用的终结点要取决于函数的类型。The endpoint you call depends on the type of function.

Note

本主题中的示例使用 cURL 工具从终端或命令提示符发送 HTTP 请求。Examples in this topic use the cURL tool to send HTTP requests from the terminal or a command prompt. 你可以使用所选的工具将 HTTP 请求发送到本地服务器。You can use a tool of your choice to send HTTP requests to the local server. 默认情况下,在基于 Linux 的系统上提供 cURL 工具。The cURL tool is available by default on Linux-based systems. 在 Windows 上,必须先下载并安装 cURL 工具On Windows, you must first download and install the cURL tool.

有关测试函数的更多常规信息,请参阅在 Azure Functions 中测试代码的策略For more general information on testing functions, see Strategies for testing your code in Azure Functions.

HTTP 和 webhook 触发的函数HTTP and webhook triggered functions

调用以下终结点,以在本地运行 HTTP 和 webhook 触发的函数:You call the following endpoint to locally run HTTP and webhook triggered functions:

http://localhost:{port}/api/{function_name}

请确保使用相同的服务器名称和 Functions 主机正在侦听的端口。Make sure to use the same server name and port that the Functions host is listening on. 在启动 Function 主机时所生成的输出中可以看到该信息。You see this in the output generated when starting the Function host. 可以使用触发器所支持的任何 HTTP 方法来调用此 URL。You can call this URL using any HTTP method supported by the trigger.

以下 cURL 命令使用查询字符串中传递的 name 参数从 GET 请求触发 MyHttpTrigger quickstart 函数。The following cURL command triggers the MyHttpTrigger quickstart function from a GET request with the name parameter passed in the query string.

curl --get http://localhost:7071/api/MyHttpTrigger?name=Azure%20Rocks

下面的示例是在请求主体中传递 name 的 POST 请求中调用的相同函数:The following example is the same function called from a POST request passing name in the request body:

curl --request POST http://localhost:7071/api/MyHttpTrigger --data '{"name":"Azure Rocks"}'

可以从在查询字符串中传递数据的浏览器发出 GET 请求。You can make GET requests from a browser passing data in the query string. 对于所有其他 HTTP 方法,必须使用 cURL、Fiddler、Postman 或类似的 HTTP 测试工具。For all other HTTP methods, you must use cURL, Fiddler, Postman, or a similar HTTP testing tool.

非 HTTP 触发的函数Non-HTTP triggered functions

对于 HTTP 触发器和 webhook 以外的所有类型函数,你可以通过调用管理终结点在本地测试函数。For all kinds of functions other than HTTP triggers and webhooks, you can test your functions locally by calling an administration endpoint. 在本地服务器上通过 HTTP POST 请求调用此终结点会触发该函数。Calling this endpoint with an HTTP POST request on the local server triggers the function. 可以选择通过 POST 请求正文将测试数据传递给执行。You can optionally pass test data to the execution in the body of the POST request. 此功能类似于 Azure 门户中的“测试”选项卡。This functionality is similar to the Test tab in the Azure portal.

可以调用以下管理员终结点以触发非 HTTP 函数:You call the following administrator endpoint to trigger non-HTTP functions:

http://localhost:{port}/admin/functions/{function_name}

若要将测试数据传递给函数的管理员终结点,必须在 POST 请求消息的正文中提供数据。To pass test data to the administrator endpoint of a function, you must supply the data in the body of a POST request message. 消息正文需要具有以下 JSON 格式:The message body is required to have the following JSON format:

{
    "input": "<trigger_input>"
}

<trigger_input> 值包含函数所需格式的数据。The <trigger_input> value contains data in a format expected by the function. 下面的 cURL 示例是指向 QueueTriggerJS 函数的 POST。The following cURL example is a POST to a QueueTriggerJS function. 在这种情况下,输入是一个字符串,等同于期望在队列中找到的消息。In this case, the input is a string that is equivalent to the message expected to be found in the queue.

curl --request POST -H "Content-Type:application/json" --data '{"input":"sample queue data"}' http://localhost:7071/admin/functions/QueueTriggerJS

在版本 1.x 中使用 func run 命令Using the func run command in version 1.x

Important

该工具的 2.x 版本不支持 func run 命令。The func run command is not supported in version 2.x of the tools. 有关详细信息,请参阅主题如何指向 Azure Functions 运行时版本For more information, see the topic How to target Azure Functions runtime versions.

也可以使用 func run <FunctionName> 直接调用函数并为函数提供输入数据。You can also invoke a function directly by using func run <FunctionName> and provide input data for the function. 此命令类似于在 Azure 门户中使用“测试”选项卡运行函数。This command is similar to running a function using the Test tab in the Azure portal.

func run 支持以下选项:func run supports the following options:

选项Option 说明Description
--content -c 内联内容。Inline content.
--debug -d 运行函数前,将调试程序附加到主机进程。Attach a debugger to the host process before running the function.
--timeout -t 本地 Functions 主机准备就绪前的等待时间(以秒为单位)。Time to wait (in seconds) until the local Functions host is ready.
--file -f 要用作内容的文件名。The file name to use as content.
--no-interactive 不提示输入。Does not prompt for input. 适用于自动化方案。Useful for automation scenarios.

例如,若要调用 HTTP 触发的函数并传递内容正文,请运行以下命令:For example, to call an HTTP-triggered function and pass content body, run the following command:

func run MyHttpTrigger -c '{\"name\": \"Azure\"}'

发布到 AzurePublish to Azure

Core Tools 支持两种类型的部署:将函数项目文件直接部署到函数应用,以及部署自定义 Linux 容器(仅在版本 2.x 中受支持)。Core Tools supports two types of deployment, deploying function project files directly to your function app and deploying a custom Linux container, which is supported only in version 2.x. 必须事先在 Azure 订阅中创建函数应用You must have already created a function app in your Azure subscription.

在版本 2.x 中,发布之前必须在项目中注册扩展In version 2.x, you must have registered your extensions in your project before publishing. 应该生成需要编译的项目,以便部署二进制文件。Projects that require compilation should be built so that the binaries can be deployed.

项目文件部署Project file deployment

最常见的部署方法涉及使用 Core Tools 打包函数应用项目、二进制文件和依赖项并将该包部署到函数应用。The most common deployment method involves using Core Tools to package your function app project, binaries, and dependencies and deploy the package to your function app. 可以选择直接从部署包运行函数You can optionally run your functions directly from the deployment package.

若要将 Functions 项目发布到 Azure 中的函数应用,使用 publish 命令:To publish a Functions project to a function app in Azure, use the publish command:

func azure functionapp publish <FunctionAppName>

此命令发布到 Azure 中的现有函数应用。This command publishes to an existing function app in Azure. 如果订阅中不存在 <FunctionAppName>,会发生错误。An error occurs when the <FunctionAppName> doesn't exist in your subscription.

publish 命令上传 Functions 项目目录的内容。The publish command uploads the contents of the Functions project directory. 如果在本地删除文件,publish 命令不会将文件从 Azure 中删除。If you delete files locally, the publish command does not delete them from Azure. 可以使用 Azure 门户中的 Kudu 工具删除 Azure 中的文件。You can delete files in Azure by using the Kudu tool in the Azure portal.

Important

在 Azure 门户中创建函数应用时,该应用默认使用 2.x 版函数运行时。When you create a function app in the Azure portal, it uses version 2.x of the Function runtime by default. 若要让函数应用使用 1.x 版运行时,请遵照在版本 1.x 上运行中的说明操作。To make the function app use version 1.x of the runtime, follow the instructions in Run on version 1.x. 无法为包含现有函数的函数应用更改运行时版本。You can't change the runtime version for a function app that has existing functions.

以下项目发布选项同时适用于 1.x 和 2.x 版本:The following project publish options apply for both versions, 1.x and 2.x:

选项Option 说明Description
--publish-local-settings -i 将 local.settings.json 中的设置发布到 Azure,如果该设置已存在,则提示进行覆盖。Publish settings in local.settings.json to Azure, prompting to overwrite if the setting already exists. 如果在使用存储仿真器,则将应用设置更改为实际的存储连接If you are using the storage emulator, you change the app setting to an actual storage connection.
--overwrite-settings -y 使用 --publish-local-settings -i 时隐藏覆盖应用设置的提示。Suppress the prompt to overwrite app settings when --publish-local-settings -i is used.

以下项目发布选项仅在版本 2.x 中受支持:The following project publish options are only supported in version 2.x:

选项Option 说明Description
--publish-settings-only -o 仅发布设置,并跳过内容。Only publish settings and skip the content. 默认为提示。Default is prompt.
--list-ignored-files 基于 .funcignore 文件显示发布期间忽略的文件列表。Displays a list of files that are ignored during publishing, which is based on the .funcignore file.
--list-included-files 基于 .funcignore 文件显示发布的文件列表。Displays a list of files that are published, which is based on the .funcignore file.
--nozip 关闭默认的 Run-From-Zip 模式。Turns the default Run-From-Zip mode off.
--build-native-deps 发布 python 函数应用时跳过生成 .wheels 文件夹。Skips generating .wheels folder when publishing python function apps.
--additional-packages 构建本机依赖项时要安装的包列表。List of packages to install when building native dependencies. 例如:python3-dev libevent-devFor example: python3-dev libevent-dev.
--force 在某些情况下会忽略预发布验证。Ignore pre-publishing verification in certain scenarios.
--csx 发布 C# 脚本 (.csx) 项目。Publish a C# script (.csx) project.
--no-build 跳过 dotnet 函数的生成。Skip building dotnet functions.
--dotnet-cli-params 发布编译的 C# (.csproj) 函数时,Core Tools 将调用“dotnet build --output bin/publish”。When publishing compiled C# (.csproj) functions, the core tools calls 'dotnet build --output bin/publish'. 传递到此选项的任何参数将追加到命令行。Any parameters passed to this will be appended to the command line.

自定义容器部署Custom container deployment

Functions 允许在自定义 Linux 容器中部署函数项目。Functions lets you deploy your function project in a custom Linux container. Core Tools 版本 2.x 支持部署自定义容器。Version 2.x of Core Tools supports deploying a custom container. 自定义容器必须有一个 Dockerfile。Custom containers must have a Dockerfile. func init 中使用 --dockerfile 选项。Use the --dockerfile option on func init.

func deploy

可使用以下自定义容器部署选项:The following custom container deployment options are available:

选项Option 说明Description
--registry 当前用户登录到的 Docker 注册表的名称。The name of a Docker Registry the current user signed-in to.
--platform 函数应用的托管平台。Hosting platform for the function app. 有效选项为 kubernetesValid options are kubernetes
--name 函数应用名称。Function app name.
--max (可选)设置要部署到的最大函数应用实例数。Optionally, sets the maximum number of function app instances to deploy to.
--min (可选)设置要部署到的最小函数应用实例数。Optionally, sets the minimum number of function app instances to deploy to.
--config 设置可选的部署配置文件。Sets an optional deployment configuration file.

后续步骤Next steps

Azure Functions Core Tools 是开源工具且托管在 GitHub 上Azure Functions Core Tools is open source and hosted on GitHub.
若要提交 bug 或功能请求,请打开 GitHub 问题To file a bug or feature request, open a GitHub issue.