使用 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.

重要

請勿在相同函式應用程式中混用本機開發與入口網站開發。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.

在您的本機電腦上開發函式, 並使用核心工具將其發佈至 Azure 時, 會遵循下列基本步驟:Developing functions on your local computer and publishing them to Azure using Core Tools follows these basic steps:

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.xVersion 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 支援的所有平台都支援這個版本,包括 WindowsmacOSLinuxThis version is supported on all platforms .NET Core 2.x supports, including Windows, macOS, and Linux.

重要

您可以使用延伸模組套件, 略過安裝 .net CORE 2.x SDK 的需求。You can bypass the requirement for installing the .NET Core 2.x SDK by using extension bundles.

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. 安裝 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.

  2. 安裝 Core Tools 套件:Install the Core Tools package:

    npm install -g azure-functions-core-tools
    

    可能需要幾分鐘的時間, npm 才能下載並安裝 Core Tools 套件。It may take a few minutes for npm to download and install the Core Tools package.

  3. 如果您不打算使用延伸模組配套, 請安裝適用于 Windows 的 .NET Core 2.x SDKIf you do not plan to use extension bundles, install the .NET Core 2.x SDK for Windows.

採用 Homebrew 的 MacOSMacOS with Homebrew

下列步驟使用 Homebrew 在 macOS 上安裝 Core Tools。The following steps use Homebrew to install the Core Tools on macOS.

  1. 如果尚未安裝 Homebrew,請加以安裝。Install Homebrew, if it's not already installed.

  2. 安裝 Core Tools 套件:Install the Core Tools package:

    brew tap azure/functions
    brew install azure-functions-core-tools
    
  3. 如果您不打算使用延伸模組配套, 請安裝適用于 MacOS 的 .NET Core 2.x SDKIf you do not plan to use extension bundles, install .NET Core 2.x SDK for macOS.

採用 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. 安裝 Microsoft 封裝存放庫 GPG 金鑰, 以驗證封裝完整性:Install the Microsoft package repository GPG key, to validate package integrity:

    curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
    sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg
    
  2. 請確認您的 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 VersionVersion
    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
  3. 安裝 Core Tools 套件:Install the Core Tools package:

    sudo apt-get install azure-functions-core-tools
    
  4. 如果您不打算使用延伸模組配套, 請安裝適用于 Linux 的 .NET Core 2.x SDKIf you do not plan to use extension bundles, install .NET Core 2.x SDK for Linux.

建立本機的 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.

Select a worker runtime:
dotnet
node
python (preview)
powershell (preview)

使用向上/向下鍵來選擇語言,然後按 Enter。Use the up/down arrow keys to choose a language, then press Enter. 如果您打算開發 JavaScript 或 TypeScript 函式, 請選擇 [ node], 然後選取語言。If you plan to develop JavaScript or TypeScript functions, choose node, and then select the language. TypeScript 有一些額外的需求TypeScript has some additional requirements.

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.

重要

根據預設,2.x 版的 Core Tools 會建立適用於 .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

除了 HTTP 和計時器觸發程序函式繫結在執行階段版本 2.x 會實作為延伸模組套件。With the exception of HTTP and timer triggers, Functions bindings in runtime version 2.x are implemented as extension packages. 在版本中的 Azure Functions 執行階段 2.x,您必須明確註冊您的函式中使用的繫結類型的擴充功能。In version 2.x of the Azure Functions runtime, you have to explicitly register the extensions for the binding types used in your functions. 此狀況的例外是 HTTP 繫結和計時器觸發程序,不需要延伸模組。The exceptions to this are HTTP bindings and timer triggers, which do not require extensions.

您可以選擇安裝個別的繫結延伸模組,或者您可以加入 host.json 專案檔案的延伸模組套件組合參考。You can choose to install binding extensions individually, or you can add an extension bundle reference to the host.json project file. 延伸模組套件組合中移除的機會便封裝相容性問題時使用多個繫結類型。Extension bundles removes the chance of having package compatibility issues when using multiple binding types. 它是建議的方法,以註冊繫結延伸模組。It is the recommended approach for registering binding extensions. 延伸模組套件組合也就不需要安裝.NET Core 2.x SDK。Extension bundles also removes the requirement of installing the .NET Core 2.x SDK.

延伸模組套件組合Extension bundles

安裝繫結擴充功能最簡單的方式是啟用擴充功能套件組合The easiest way to install binding extensions is to enable extension bundles. 當您啟用套件組合時,系統會自動安裝一組預先定義的擴充功能套件。When you enable bundles, a predefined set of extension packages is automatically installed.

若要啟用擴充功能套件組合,請開啟 host.json 檔案,並更新其內容以符合下列程式碼:To enable extension bundles, open the host.json file and update its contents to match the following code:

{
    "version": "2.0",
    "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[1.*, 2.0.0)"
    }
}

若要進一步了解,請參閱註冊 Azure Functions 繫結延伸模組To learn more, see Register Azure Functions binding extensions. 您應該先 functions.json 檔案中加入繫結加入 host.json 延伸模組套件組合。You should add extension bundles to the host.json before you add bindings to the functions.json file.

註冊個別的擴充功能Register individual extensions

如果您需要安裝擴充功能不在組合中,您可以手動註冊特定的繫結的個別擴充功能封裝。If you need to install extensions that aren't in a bundle, you can manually register individual extension packages for specific bindings.

注意

若要使用手動註冊擴充功能func extensions install,您必須有.NET Core 2.x 安裝 SDK。To manually register extensions by using func extensions install, you must have the .NET Core 2.x SDK installed.

在更新 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.

本機設定檔Local settings file

本機的設定檔案會儲存應用程式設定、連接字串, 以及本機開發工具所使用的設定。The local.settings.json file stores app settings, connection strings, and settings used by local development tools. 只有當您在本機執行專案時, 才會使用本機. 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. 這些索引鍵/值 (字串字串) 組會對應至 Azure 中函數應用程式中的應用程式AzureWebJobsStorage設定, 例如。These key-value (string-string) pairs correspond to application settings in your function app in Azure, like AzureWebJobsStorage. 許多觸發程式和系結都有參考連接字串應用程式設定的屬性, Connection例如Blob 儲存體觸發程式。Many 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.
AzureWebJobsStorage是 HTTP 以外的觸發程式所需的應用程式設定。AzureWebJobsStorage is a required app setting for triggers other than HTTP.
2.x 版的函式執行時間需要 [FUNCTIONS_WORKER_RUNTIME] 設定, 這是由核心工具針對您的專案所產生的。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 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 當您在本機執行專案時, 此區段中的設定會自訂函式主機進程。Settings in this section customize the Functions host process when you run projects locally. 這些設定與主機. 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區段取得連接字串的架構, 例如Entity Framework, 才會使用這個集合。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 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 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
Event Grid 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.

2.x 版Version 2.x

在2.x 版的執行時間中, 視您的專案語言而定, start 命令會有所不同。In version 2.x of the runtime, the start command varies, depending on your project language.

C#C#

func start --build

JavaScriptJavaScript

func start

TypeScriptTypeScript

npm install
npm start     

1.x 版Version 1.x

1.x 版的函式執行時間需要host命令, 如下列範例所示:Version 1.x of the Functions runtime requires the host command, as in the following example:

func host start

func start 支援下列選項:func 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 允許跨來源的已驗證要求 (也就是 cookie 及驗證標頭) 僅限 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# 類別庫專案時,將會以類似於 MyProject/bin/Debug/netstandard2.0 的路徑在 root 子資料夾中產生 host.json、local.settings.json 和 function.json 等檔案。For 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.

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

重要

在本機執行時,不會對 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

若要在本機測試您的函式,您要使用 HTTP 要求在本機伺服器上啟動 Functions 主機並呼叫端點。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.

注意

本主題中的範例使用 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 為基礎的系統和 Windows 10 組建17063及更新版本上, 預設會提供捲曲的工具。The cURL tool is available by default on Linux-based systems and Windows 10 build 17063 and later. 在較舊的 Windows 上, 您必須先下載並安裝捲曲的工具On older 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 命令從 GET 要求在查詢字串中傳遞 name 參數,觸發 MyHttpTrigger 快速入門函式。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

下列範例與從 POST 要求在要求本文中傳遞 name 所呼叫的函式相同: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 範例是 POST 到 QueueTriggerJS 函式。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

重要

工具的版本 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

此 Azure Functions Core Tools 支援兩種部署類型: 透過Zip 部署部署自訂 Docker 容器, 將函式專案檔直接部署至函式應用程式。The Azure Functions Core Tools supports two types of deployment: deploying function project files directly to your function app via Zip Deploy and deploying a custom Docker container. 您必須已在 Azure 訂用帳戶中建立函式應用程式, 您將在其中部署您的程式碼。You must have already created a function app in your Azure subscription, to which you'll deploy your code. 應建置需要編譯的專案,以便部署二進位檔。Projects that require compilation should be built so that the binaries can be deployed.

專案資料夾可能包含不應發行的特定語言檔案和目錄。A project folder may contain language-specific files and directories that shouldn't be published. 排除的專案會列在根專案資料夾中的 funcignore 檔案中。Excluded items are listed in a .funcignore file in the root project folder.

部署 (專案檔)Deployment (project files)

若要將您的本機程式碼發佈至 Azure 中的函數publish應用程式, 請使用命令:To publish your local code 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>不存在於訂用帳戶中的, 將會收到錯誤。You'll get an error if you try to publish to a <FunctionAppName> that doesn't exist in your subscription. 若要了解如何使用 Azure CLI 從命令提示字元或終端機視窗建立函式應用程式,請參閱建立無伺服器也可執行的函式應用程式To learn how to create a function app from the command prompt or terminal window using the Azure CLI, see Create a Function App for serverless execution. 根據預設, 此命令會將您的應用程式部署為從部署套件執行By default, this command deploys your app to run from the deployment package. 若要停用這個建議的部署模式--nozip , 請使用選項。To disable this recommended deployment mode, use the --nozip option.

重要

當您在 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 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, first 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 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-Package 模式。Turns the default Run-From-Package 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.

部署 (自訂容器)Deployment (custom container)

Azure Functions 可讓您在自訂的 Docker 容器中部署函數專案。Azure Functions lets you deploy your function project in a custom Docker container. 如需詳細資訊,請參閱使用自訂映像在 Linux 上建立函式For more information, see Create a function on Linux using a custom image. 自訂容器必須具有 Dockerfile。Custom containers must have a Dockerfile. 若要建立具有 Dockerfile 的應用程式, 請使用上func init的--Dockerfile 選項。To create an app with a 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.

監視函式Monitoring functions

若要監視函式的執行, 建議的方法是與 Azure 應用程式 Insights 整合。The recommended way to monitor the execution of your functions is by integrating with Azure Application Insights. 您也可以將執行記錄串流至本機電腦。You can also stream execution logs to your local computer. 若要深入了解,請參閱監視 Azure FunctionsTo learn more, see Monitor Azure Functions.

啟用 Application Insights 整合Enable Application Insights integration

當您在 Azure 入口網站中建立函數應用程式時, 預設會為您完成 Application Insights 整合。When you create a function app in the Azure portal, the Application Insights integration is done for you by default. 不過,當您使用 Azure CLI 建立函式應用程式時,則不會在 Azure 中完成您的函式應用程式整合。However, when you create your function app by using the Azure CLI, the integration in your function app in Azure isn't done.

函式可讓您輕鬆地從 Azure 入口網站中,將 Application Insights 整合新增至函式應用程式。Functions makes it easy to add Application Insights integration to a function app from the Azure portal.

  1. 入口網站中,選取 [所有服務] > [函式應用程式] ,然後選取函式應用程式,接著在視窗頂端選取 [Application Insights] 橫幅In the portal, select All services > Function Apps, select your function app, and then select the Application Insights banner at the top of the window

    從入口網站啟用 Application Insights

  2. 使用資料表 (圖片下方) 中指定的設定,建立 Application Insights 資源。Create an Application Insights resource by using the settings specified in the table below the image.

    建立 Application Insights 資源

    設定Setting 建議的值Suggested value 說明Description
    名稱Name 唯一的應用程式名稱Unique app name 最簡單的方式是使用與您函式應用程式一樣的名稱,而這必須是您訂用帳戶中唯一的名稱。It's easiest to use the same name as your function app, which must be unique in your subscription.
    位置Location 西歐West Europe 可能的話,請使用與函式應用程式相同的區域,或該區域附近的區域。If possible, use the same region as your function app, or one that's close to that region.
  3. 選取 [確定] 。Select OK. Application Insights 資源會建立在函式應用程式所在的資源群組和訂用帳戶。The Application Insights resource is created in the same resource group and subscription as your function app. 建立資源之後,請關閉 Application Insights 視窗。After the resource is created, close the Application Insights window.

  4. 回到您的函式應用程式中,選取 [應用程式設定] ,然後向下捲動至 [應用程式設定] 。Back in your function app, select Application settings, and then scroll down to Application settings. 如果您看到名為 APPINSIGHTS_INSTRUMENTATIONKEY 的設定,表示 Azure 中執行的函式應用程式已啟用 Application Insights 整合。If you see a setting named APPINSIGHTS_INSTRUMENTATIONKEY, Application Insights integration is enabled for your function app running in Azure.

啟用串流記錄Enable streaming logs

您可以在本機電腦上的命令列會話中, 查看您的函式所產生的記錄檔串流。You can view a stream of log files being generated by your functions in a command-line session on your local computer.

原生串流記錄Native streaming logs

內建記錄資料流程Built-in log streaming

logstream使用選項來開始接收在 Azure 中執行之特定函式應用程式的串流記錄, 如下列範例所示:Use the logstream option to start receiving streaming logs of a specific function app running in Azure, as in the following example:

func azure functionapp logstream <FunctionAppName>

即時計量資料流Live Metrics Stream

您也可以藉由包含--browser選項, 在新的瀏覽器視窗中查看函數應用程式的即時計量資料流, 如下列範例所示:You can also view the Live Metrics Stream for your function app in a new browser window by including the --browser option, as in the following example:

func azure functionapp logstream <FunctionAppName> --browser

這種類型的串流處理記錄檔需要您為函式應用程式啟用 Application Insights 整合This type of streaming logs requires that you enable Application Insights integration for your function app.

後續步驟Next steps

Azure Functions Core Tools 是開放原始碼且裝載於 GitHub 上Azure Functions Core Tools is open source and hosted on GitHub.
若要提出錯誤或功能要求,請開啟 GitHub 問題To file a bug or feature request, open a GitHub issue.