使用 Visual Studio 來開發 Azure FunctionsDevelop Azure Functions using Visual Studio

Visual Studio 可讓您開發、測試類別庫C#函式,並將其部署至 Azure。Visual Studio lets you develop, test, and deploy C# class library functions to Azure. 如果這是您第一次體驗 Azure Functions,可至 Azure Functions 簡介深入了解。If this experience is your first with Azure Functions, you can learn more at An introduction to Azure Functions.

Visual Studio 在開發函數時提供下列優點:Visual Studio provides the following benefits when develop your functions:

  • 在本機開發電腦上編輯、建置及執行函數。Edit, build, and run functions on your local development computer.
  • 將您的 Azure Functions 專案直接發佈至 Azure,並視需要建立 Azure 資源。Publish your Azure Functions project directly to Azure, and create Azure resources as needed.
  • 使用C#屬性,直接在程式C#代碼中宣告函數系結。Use C# attributes to declare function bindings directly in the C# code.
  • 開發及部署預先編譯的 C# 函數。Develop and deploy pre-compiled C# functions. 預先編譯的函數提供的冷啟動效能比 C# 指令碼型函數更好。Pre-complied functions provide a better cold-start performance than C# script-based functions.
  • 在 C# 中編寫函數,同時享有 Visual Studio 開發的所有優點。Code your functions in C# while having all of the benefits of Visual Studio development.

本文提供如何使用 Visual Studio 來開發C#類別庫函式,並將其發佈至 Azure 的詳細資料。This article provides details about how to use Visual Studio to develop C# class library functions and publish them to Azure. 閱讀本文之前,您應該先完成適用於 Visual Studio 的 Functions 快速入門Before you read this article, you should complete the Functions quickstart for Visual Studio.

除非另有說明,否則顯示的程式和範例適用于 Visual Studio 2019。Unless otherwise noted, procedures and examples shown are for Visual Studio 2019.

先決條件Prerequisites

從 Visual Studio 2017 開始,Azure Functions 工具會包含在 Visual Studio 的 Azure 開發工作負載中。Azure Functions Tools is included in the Azure development workload of Visual Studio starting with Visual Studio 2017. 請確定您在 Visual Studio 安裝中包含Azure 開發工作負載。Make sure you include the Azure development workload in your Visual Studio installation.

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.

您需要的其他資源(例如 Azure 儲存體帳戶)會在發佈程式期間,于您的訂用帳戶中建立。Other resources that you need, such as an Azure Storage account, are created in your subscription during the publishing process.

注意

在 Visual Studio 2017 中,Azure 開發工作負載會將 Azure Functions 工具安裝為個別的延伸模組。In Visual Studio 2017, the Azure development workload installs the Azure Functions Tools as a separate extension. 當您更新 Visual Studio 2017 時,也請確定您使用的是最新版本的 Azure Functions 工具。When you update your Visual Studio 2017, also make sure that you are using the most recent version of the Azure Functions tools. 下列各節說明如何檢查和(如有需要)更新 Visual Studio 2017 中的 Azure Functions 工具延伸模組。The following sections show you how to check and (if needed) update your Azure Functions Tools extension in Visual Studio 2017.

使用 Visual Studio 2019 時,請略過這一節。Please skip these section when using Visual Studio 2019.

檢查 Visual Studio 2017 中的工具版本Check your tools version in Visual Studio 2017

  1. 在 [工具] 功能表中,選擇 [擴充功能和更新]。From the Tools menu, choose Extensions and Updates. 展開 [已安裝] > [工具],然後選擇 [Azure Functions 與 Web 工作工具]。Expand Installed > Tools and choose Azure Functions and Web Jobs Tools.

    驗證 Functions 工具版本

  2. 記下已安裝的版本Note the installed Version. 您可以比較此版本版本資訊中所列的最新版本。You can compare this version with the latest version listed in the release notes.

  3. 如果您的版本較舊,請依照下一節中的說明在 Visual Studio 中更新您的工具。If your version is older, update your tools in Visual Studio as shown in the following section.

在 Visual Studio 2017 中更新您的工具Update your tools in Visual Studio 2017

  1. 在 [延伸模組和更新] 對話方塊中,展開 [更新] > [Visual Studio Marketplace],選擇 [Azure Functions 與 Web 工作工具],然後選取 [更新]。In the Extensions and Updates dialog, expand Updates > Visual Studio Marketplace, choose Azure Functions and Web Jobs Tools and select Update.

    更新 Functions 工具版本

  2. 下載工具更新之後,請關閉 Visual Studio,以使用 VSIX 安裝程式觸發工具更新。After the tools update is downloaded, close Visual Studio to trigger the tools update using the VSIX installer.

  3. 在安裝程式中選擇 [確定] 以啟動,然後選擇 [修改] 以更新工具。In the installer, choose OK to start and then Modify to update the tools.

  4. 更新完成後,請選擇 [關閉] 並重新啟動 Visual Studio。After the update is complete, choose Close and restart Visual Studio.

注意

在 Visual Studio 2019 和更新版本中,Azure Functions 工具延伸模組會在 Visual Studio 中更新。In Visual Studio 2019 and later, the Azure Functions tools extension is updated as part of Visual Studio.

建立 Azure Functions 專案Create an Azure Functions project

Visual Studio 中的 Azure Functions 專案範本會建立可發行至 Azure 中函式應用程式的專案。The Azure Functions project template in Visual Studio creates a project that can be published to a function app in Azure. 您可以使用函式應用程式將多個函式群組為邏輯單位,以便您管理、部署和共用資源。You can use a function app to group functions as a logical unit for management, deployment, and sharing of resources.

  1. 在 Visual Studio 中,於 [檔案] 功能表上選取 [新增] > [專案] 。In Visual Studio, on the File menu, select New > Project.

  2. 在 [建立新專案] 對話方塊中,搜尋 functions,選擇 [Azure Functions] 範本,然後選取 [下一步] 。In the Create a new project dialog box, search for functions, choose the Azure Functions template, and select Next.

  3. 輸入專案的名稱,然後選取 [建立] 。Enter a name for your project, and select Create. 函式應用程式名稱必須是有效的 C# 命名空間,因此不會使用底線、連字號或任何其他非英數字元。The function app name must be valid as a C# namespace, so don't use underscores, hyphens, or any other nonalphanumeric characters.

  4. 在 [建立新的 Azure Functions 應用程式] 中,使用下列選項:In Create a new Azure Functions application, use the following options:

    • Azure Functions v2 (.NET Core) 1Azure Functions v2 (.NET Core) 1
    • HTTP 觸發程序HTTP trigger
    • 儲存體帳戶儲存體模擬器Storage Account: Storage Emulator
    • 授權層級 匿名Authorization level: Anonymous
    選項Option 建議的值Suggested value 說明Description
    Functions 執行階段Functions runtime Azure Functions 2.x
    (.NET Core)
    Azure Functions 2.x
    (.NET Core)
    此設定會建立使用 Azure Functions 2.x 版執行階段 (支援 .NET Core) 的函式專案。This setting creates a function project that uses the version 2.x runtime of Azure Functions, which supports .NET Core. Azure Functions 1.x 支援 .NET Framework。Azure Functions 1.x supports the .NET Framework. 如需詳細資訊,請參閱設定 Azure Functions 執行階段目標版本For more information, see Target Azure Functions runtime version.
    函式範本Function template HTTP 觸發程序HTTP trigger 此設定會建立 HTTP 要求所觸發的函式。This setting creates a function triggered by an HTTP request.
    儲存體帳戶Storage Account 儲存體模擬器Storage Emulator HTTP 觸發程序不會使用 Azure 儲存體帳戶連線。An HTTP trigger doesn't use the Azure Storage account connection. 其他所有觸發程序類型都需要有效的儲存體帳戶連接字串。All other trigger types require a valid Storage account connection string. 因為 Functions 需要儲存體帳戶,所以當您將專案發佈至 Azure 時,就會指派或建立一個。Because Functions requires a storage account, one is assigned or created when you publish your project to Azure.
    授權層級Authorization level 匿名Anonymous 建立的函式可以由任何用戶端觸發,而不需提供金鑰。The created function can be triggered by any client without providing a key. 此授權設定可以讓測試新函式變得簡單。This authorization setting makes it easy to test your new function. 如需金鑰和授權的詳細資訊,請參閱 HTTP 和 Webhook 繫結中的授權金鑰For more information about keys and authorization, see Authorization keys in the HTTP and webhook bindings.

    注意

    請確定您已將 [授權層級] 設定為 AnonymousMake sure you set the Authorization level to Anonymous. 如果您選擇預設層級 Function 時,必須在要求中提供函式金鑰以存取您的函式端點。If you choose the default level of Function, you're required to present the function key in requests to access your function endpoint.

  5. 選取 [建立] 以建立函式專案和由 HTTP 觸發的函式。Select Create to create the function project and HTTP-triggered function.

專案範本會建立 C# 專案,安裝 Microsoft.NET.Sdk.Functions NuGet 套件,並設定目標架構。The project template creates a C# project, installs the Microsoft.NET.Sdk.Functions NuGet package, and sets the target framework. 新專案含有下列檔案:The new project has the following files:

  • host.json:讓您設定 Functions 主機。host.json: Lets you configure the Functions host. 這些設定同時適用於在本機執行及在 Azure 中執行。These settings apply both when running locally and in Azure. 如需詳細資訊,請參閱 host.json 參考For more information, see host.json reference.

  • local.settings.json:維持在本機執行函數時所使用的設定。local.settings.json: Maintains settings used when running functions locally. 在 Azure 中執行時,不會使用這些設定。These settings aren't used when running in Azure. 如需詳細資訊,請參閱本機設定檔For more information, see Local settings file.

    重要

    由於 local.settings.json 檔案可以包含祕密,因此,您必須從專案原始檔控制中排除它。Because the local.settings.json file can contain secrets, you must excluded it from your project source control. 這個檔案的 [複製到輸出目錄] 設定應該一律是 [有更新時才複製]。The Copy to Output Directory setting for this file should always be Copy if newer.

如需詳細資訊,請參閱 Functions 類別庫專案For more information, see Functions class library project.

本機設定檔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 中函數應用程式中的應用程式設定,例如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.
AzureWebJobsStorage是 HTTP 以外的觸發程式所需的應用程式設定。AzureWebJobsStorage is a required app setting for triggers other than HTTP.
2.x 版和更新版本的函式執行時間需要 [FUNCTIONS_WORKER_RUNTIME] 設定,這是由核心工具針對您的專案所產生的。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 當您在本機執行專案時,此區段中的設定會自訂函式主機進程。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 FrameworkThis 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.

在您發行專案時,不會自動上傳 json 中的設定。Settings in local.settings.json aren't uploaded automatically when you publish the project. 若要確定這些設定也存在於 Azure 中的函式應用程式,您必須在發佈專案之後上傳它們。To make sure that these settings also exist in your function app in Azure, you must upload them after you publish your project. 若要深入瞭解,請參閱函數應用程式設定To learn more, see Function app settings.

ConnectionStrings 中的值永遠不會發佈。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 Environment variables.

設定專案以進行本機開發Configure the project for local development

函數執行階段會在內部使用 Azure 儲存體帳戶。The Functions runtime uses an Azure Storage account internally. 針對 HTTP 和 Webhook 以外的所有觸發程序類型,您必須將 Values.AzureWebJobsStorage 機碼設定為有效的 Azure 儲存體帳戶連接字串。For all trigger types other than HTTP and webhooks, you must set the Values.AzureWebJobsStorage key to a valid Azure Storage account connection string. 函式應用程式也可以針對專案所需的 AzureWebJobsStorage 連線設定,使用 Azure 儲存體模擬器Your function app can also use the Azure storage emulator for the AzureWebJobsStorage connection setting that is required by the project. 若要使用模擬器,將 AzureWebJobsStorage 的值設定為 UseDevelopmentStorage=trueTo use the emulator, set the value of AzureWebJobsStorage to UseDevelopmentStorage=true. 在部署之前,請將此設定變更為實際的儲存體帳戶連接字串。Change this setting to an actual storage account connection string before deployment.

設定儲存體帳戶連接字串:To set the storage account connection string:

  1. 在 Visual Studio 中,開啟 [ Cloud Explorer],展開儲存體帳戶 ** > 儲存體帳戶**,然後在 [屬性] 索引標籤中複製 [**主要連接字串**] 值。In Visual Studio, open Cloud Explorer, expand Storage Account > Your Storage Account, then in the Properties tab 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. 重複上一步,針對函數所需的其他任何連接,將唯一機碼新增至 [值] 陣列。Repeat the previous step to add unique keys to the Values array for any other connections required by your functions.

將函式新增至您的專案Add a function to your project

在C#類別庫函式中,函數所使用的系結是透過在程式碼中套用屬性來定義。In C# class library functions, the bindings used by the function are defined by applying attributes in the code. 當您從提供的範本建立函數觸發程式時,會為您套用觸發程式屬性。When you create your function triggers from the provided templates, the trigger attributes are applied for you.

  1. 在 [方案總管] 中,於專案節點上按一下滑鼠右鍵,然後選取 [新增] > [新項目]。In Solution Explorer, right-click on your project node and select Add > New Item. 選取 [Azure 函數],輸入類別的 [名稱],然後按一下 [新增]。Select Azure Function, type a Name for the class, and click Add.

  2. 選擇您的觸發程序,設定繫結屬性,然後按一下 [建立]。Choose your trigger, set the binding properties, and click Create. 下列範例顯示建立佇列儲存體觸發之函數時的設定。The following example shows the settings when creating a Queue storage triggered function.

    建立由佇列觸發的函式

    這個觸發程序範例會使用連接字串,具有名為 QueueStorage 的索引鍵。This trigger example uses a connection string with a key named QueueStorage. 此連接字串設定必須在 local.settings.json 檔案中定義。This connection string setting must be defined in the local.settings.json file.

  3. 檢查新加入的類別。Examine the newly added class. 您會看到靜態 [執行] 方法,它是使用 FunctionName 屬性來屬性化。You see a static Run method, that is attributed with the FunctionName attribute. 這個屬性指出該方法是函數的進入點。This attribute indicates that the method is the entry point for the function.

    例如,下列 C# 類別代表基本佇列儲存體觸發的函數:For example, the following C# class represents a basic Queue storage triggered function:

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

    會將繫結特定屬性套用至提供給進入點方法的每個繫結參數。A binding-specific attribute is applied to each binding parameter supplied to the entry point method. 屬性會將繫結資訊作為參數使用。The attribute takes the binding information as parameters. 在上述範例中,第一個參數套用了 QueueTrigger 屬性,指出佇列觸發的函數。In the previous example, the first parameter has a QueueTrigger attribute applied, indicating queue triggered function. 佇列名稱和連接字串設定名稱會作為參數傳遞至 QueueTrigger 屬性。The queue name and connection string setting name are passed as parameters to the QueueTrigger attribute. 如需詳細資訊,請參閱 Azure Functions 的 Azure 佇列儲存體繫結For more information, see Azure Queue storage bindings for Azure Functions.

您可以使用上述程序,對函式應用程式專案新增更多函式。You can use the above procedure to add more functions to your function app project. 專案中的每個函式都可以有不同的觸發程序,但函式必須只有一個觸發程序。Each function in the project can have a different trigger, but a function must have exactly one trigger. 如需詳細資訊,請參閱 Azure Functions 觸發程序和繫結概念For more information, see Azure Functions triggers and bindings concepts.

新增繫結Add bindings

和觸發程序一樣,輸入和輸出繫結會新增至函式作為繫結屬性。As with triggers, input and output bindings are added to your function as binding attributes. 請將繫結新增至函式,如下所示:Add bindings to a function as follows:

  1. 請確定您已設定專案以進行本機開發Make sure you've configured the project for local development.

  2. 為特定繫結新增適當的 NuGet 擴充功能套件。Add the appropriate NuGet extension package for the specific binding. 如需詳細資訊,請參閱<觸發程序和繫結>一文中的使用 Visual Studio 的本機 C# 開發For more information, see Local C# development using Visual Studio in the Triggers and Bindings article. 繫結專屬的 NuGet 套件需求可於繫結的參考文章中找到。The binding-specific NuGet package requirements are found in the reference article for the binding. 例如,您可以在事件中樞繫結參考文章中尋找事件中樞觸發程序的套件需求。For example, find package requirements for the Event Hubs trigger in the Event Hubs binding reference article.

  3. 如果有繫結所需的應用程式設定,請將其新增至本機設定檔案中的集合。If there are app settings that the binding needs, add them to the Values collection in the local setting file. 當函式在本機執行時,就會使用這些值。These values are used when the function runs locally. 當函式在 Azure 中的函式應用程式中執行時,則會使用函式應用程式設定When the function runs in the function app in Azure, the function app settings are used.

  4. 在方法簽章中新增適當的繫結屬性。Add the appropriate binding attribute to the method signature. 在下列範例中,佇列訊息會觸發函式,而且輸出繫結會在不同的佇列中,使用相同文字建立新的佇列訊息。In the following example, a queue message triggers the function, and the output binding creates a new queue message with the same text in a different queue.

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

    佇列儲存體的連接是從 AzureWebJobsStorage 設定中取得的。The connection to Queue storage is obtained from the AzureWebJobsStorage setting. 如需詳細資訊,請參閱特定繫結的參考文章。For more information, see the reference article for the specific binding.

下表顯示 Azure Functions 執行時間的主要版本所支援的系結:This table shows the bindings that are supported in the major versions of the Azure Functions runtime:

TypeType 1.x1.x 2.x 和更新版本12.x and higher1 觸發程序Trigger 輸入Input 輸出Output
Blob 儲存體Blob storage
Cosmos DBCosmos DB
Event GridEvent 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
TwilioTwilio

1從版本2.x 執行時間開始,必須註冊 HTTP 和計時器以外的所有系結。1 Starting with the version 2.x runtime, all bindings except HTTP and Timer must be registered. 請參閱註冊繫結延伸模組See Register binding extensions.

測試函式Testing functions

Azure Functions Core Tools 可讓您在本機開發電腦上執行 Azure Functions 專案。Azure Functions Core Tools lets you run Azure Functions project on your local development computer. 第一次從 Visual Studio 啟動函式時,系統會提示您安裝這些工具。You are prompted to install these tools the first time you start a function from Visual Studio.

若要測試您的函式,請按 F5。To test your function, press F5. 如果出現提示,接受來自 Visual Studio 之下載及安裝 Azure Functions Core (CLI) 工具的要求。If prompted, accept the request from Visual Studio to download and install Azure Functions Core (CLI) tools. 您可能也需要啟用防火牆例外狀況,工具才能處理 HTTP 要求。You may also need to enable a firewall exception so that the tools can handle HTTP requests.

隨著專案的執行,您可以像測試部署函數一樣測試程式碼。With the project running, you can test your code as you would test deployed function. 如需詳細資訊,請參閱在 Azure Functions 中測試程式碼的策略For more information, see Strategies for testing your code in Azure Functions. 在偵錯模式下執行時,會依預期在 Visual Studio 中遇到中斷點。When running in debug mode, breakpoints are hit in Visual Studio as expected.

若要深入了解如何使用 Azure Functions Core Tools,請參閱在本機撰寫和測試 Azure Functions 程式碼To learn more about using the Azure Functions Core Tools, see Code and test Azure functions locally.

發佈至 AzurePublish to Azure

從 Visual Studio 發佈時,會使用兩種部署方法的其中一個:When publishing from Visual Studio, one of two deployment methods are used:

使用下列步驟,將您的專案發行至 Azure 中的函數應用程式。Use the following steps to publish your project to a function app in Azure.

  1. 在 [方案總管] 中,以滑鼠右鍵按一下專案並選取 [發佈] 。In Solution Explorer, right-click the project and select Publish.

  2. 在 [挑選發佈目標] 對話方塊中,使用影像下方表格中所指定的發佈選項:In the Pick a publish target dialog, use the publish options as specified in the table below the image:

    挑選發行目標

    選項Option 說明Description
    Azure Functions 取用方案Azure Functions Consumption plan 當您將專案發佈至在取用方案中執行的函式應用程式時,您只需支付您的函式應用程式執行費用。When you publish your project to a function app that runs in a Consumption plan, you only pay for executions of your functions app. 其他主控方案會產生較高的成本。Other hosting plans incur higher costs. 若要深入了解,請參閱 Azure Functions 規模調整和主控To learn more, see Azure Functions scale and hosting.
    建立新項目Create new 在 Azure 中會建立具有相關資源的新函式應用程式。A new function app, with related resources, is created in Azure. 當您選擇 [選取現有的] ,Azure 中現有函式應用程式的所有檔案都會以本機專案中的檔案加以覆寫。When you choose Select Existing, all files in the existing function app in Azure are overwritten by files from the local project. 請在將更新重新發佈至現有函式應用程式時,才使用此選項。Only use this option when republishing updates to an existing function app.
    從套件檔案執行Run from package file 您的函式應用程式會使用已啟用從套件執行模式的 Zip 部署來部署。Your function app is deployed using Zip Deploy with Run-From-Package mode enabled. 這是執行函式的建議方法,其可產生更好的效能。This is the recommended way of running your functions, which results in better performance. 若不使用此選項,請務必在發佈到 Azure 前,先停止在本機執行函式應用程式專案。When not using this option, make sure to stop your function app project from running locally before you publish to Azure.
  3. 選取 [發佈] 。Select Publish. 如果您尚未從 Visual Studio 登入您的 Azure 帳戶,請選取 [登入] 。If you haven't already signed-in to your Azure account from Visual Studio, select Sign-in. 您也可以建立免費 Azure 帳戶。You can also create a free Azure account.

  4. 在 [App Service: 新建] 對話方塊中,使用影像下方表格中指定的 [主控] 設定:In the App Service: Create new dialog, use the Hosting settings as specified in the table below the image:

    建立 App Service 對話方塊

    設定Setting 建議的值Suggested value 說明Description
    名稱Name 全域唯一的名稱Globally unique name 用以唯一識別新函式應用程式的名稱。Name that uniquely identifies your new function app. 有效字元是 a-z0-9-Valid characters are a-z, 0-9, and -.
    訂用帳戶Subscription 選擇您的訂用帳戶Choose your subscription 要使用的 Azure 訂用帳戶。The Azure subscription to use.
    資源群組Resource Group myResourceGroupmyResourceGroup 要在其中建立函式應用程式的資源群組名稱。Name of the resource group in which to create your function app. 選擇 [新增] 以建立新的資源群組。Choose New to create a new resource group.
    主控方案Hosting Plan 取用方案Consumption plan 在您選取 [新增] 以建立無伺服器方案之後,請務必選擇 [大小] 之下的 [取用] 。Make sure to choose the Consumption under Size after you select New to create a serverless plan. 或者,在區域中選擇您附近的 [位置] ,或選擇與函式將會存取之其他服務接近的位置。Also, choose a Location in a region near you or near other services your functions access. 取用以外的方案中執行時,您必須管理函式應用程式的調整When you run in a plan other than Consumption, you must manage the scaling of your function app.
    Azure 儲存體Azure Storage 一般用途的儲存體帳戶General-purpose storage account Functions 執行階段需要 Azure 儲存體帳戶。An Azure storage account is required by the Functions runtime. 選取 [新增] 以建立一般用途的儲存體帳戶。Select New to create a general-purpose storage account. 您也可以使用符合儲存體帳戶需求的現有帳戶。You can also use an existing account that meets the storage account requirements.
  5. 選取 [建立] 以在 Azure 中使用這些設定建立函式應用程式和相關資源,並且部署函式專案程式碼。Select Create to create a function app and related resources in Azure with these settings and deploy your function project code.

  6. 部署完成之後,請記下 [網站 URL] 值,這是 Azure 中您函式應用程式的位址。After the deployment is complete, make a note of the Site URL value, which is the address of your function app in Azure.

    發行成功訊息

函數應用程式設定Function app settings

您在 local.settings.json 中所新增的所有設定,也必須新增至 Azure 中的函式應用程式。Any settings you added in the local.settings.json must be also added to the function app in Azure. 當您發行專案時,不會自動上傳這些設定。These settings aren't uploaded automatically when you publish the project.

將必要設定上傳至 Azure 中函式應用程式的最簡單方式,是使用管理應用程式設定... 連結,該連結會在您成功發行專案之後顯示。The easiest way to upload the required settings to your function app in Azure is to use the Manage Application Settings... link that is displayed after you successfully publish your project.

這會顯示函式應用程式的 [應用程式設定] 對話方塊,您可以在其中新增新的應用程式設定或修改現有的設定。This displays the Application Settings dialog for the function app, where you can add new application settings or modify existing ones.

[本機] 代表 local.settings.json 檔案中的一個設定值,而 [遠端] 是 Azure 的函式應用程式中的目前設定。Local represents a setting value in the local.settings.json file, and Remote is the current setting in the function app in Azure. 選擇 [新增設定] 來建立新的應用程式設定。Choose Add setting to create a new app setting. 使用 [從本機插入值] 連結,將設定值複製到 [遠端] 欄位。Use the Insert value from Local link to copy a setting value to the Remote field. 當您選取 [確定] 時,暫止的變更會寫入至本機設定檔案和函式應用程式。Pending changes are written to the local settings file and the function app when you select OK.

注意

根據預設,不會將本機. settings. json 檔案簽入原始檔控制中。By default, the local.settings.json file is not checked into source control. 這表示當您從原始檔控制複製區域函式專案時,專案不會有本機. 設定 json 檔案。This means that when you clone a local Functions project from source control, the project doesn't have a local.settings.json file. 在此情況下,您必須手動在專案根目錄中建立本機. 設定的 json 檔案,讓 [應用程式設定] 對話方塊如預期般運作。In this case, you need to manually create the local.settings.json file in the project root so that the Application Settings dialog works as expected.

您也可以使用下列其中一種方式管理應用程式設定:You can also manage application settings in one of these other ways:

監視函式Monitoring functions

若要監視您的函式的執行情況,建議您整合您的函式應用程式與 Azure Application Insights。The recommended way to monitor the execution of your functions is by integrating your function app with Azure Application Insights. 當您在 Azure 入口網站中建立函式應用程式時,系統會依預設為您完成這項整合。When you create a function app in the Azure portal, this integration is done for you by default. 不過,當您在 Visual Studio 發佈期間建立函式應用程式時,則不會完成您的函式應用程式在 Azure 中的整合。However, when you create your function app during Visual Studio publishing, the integration in your function app in Azure isn't done.

若要為您的函式應用程式啟用 Application Insights:To enable Application Insights for your function app:

函式可讓您輕鬆地從 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.

若要深入了解,請參閱監視 Azure FunctionsTo learn more, see Monitor Azure Functions.

後續步驟Next steps

若要深入了解 Azure Functions Core Tools,請參閱在本機撰寫和測試 Azure Functions 程式碼To learn more about the Azure Functions Core Tools, see Code and test Azure functions locally.

若要深入了解如何將函式開發為 .NET 類別庫,請參閱 Azure Functions C# 開發人員參考To learn more about developing functions as .NET class libraries, see Azure Functions C# developer reference. 本文也會連結至範例以示範如何使用屬性宣告 Azure Functions 所支援的各種繫結類型。This article also links to examples of how to use attributes to declare the various types of bindings supported by Azure Functions.