教學課程:開始使用 Azure FunctionsTutorial: Getting started with Azure Functions

在此實驗室中,您將了解如何開始使用 Visual Studio for Mac 建置 Azure 函式。In this lab, you'll learn how to get started building Azure Functions using Visual Studio for Mac. 您也將與代表 Azure Functions 開發人員可用之多種繫結和觸發程序的其中一種 Azure 儲存體資料表進行整合。You'll also integrate with Azure storage tables, which represent one of the many kinds of bindings and triggers available to Azure Functions developers.

目標Objectives

  • 建立及偵錯區域 Azure 函式Create and debug local Azure Functions
  • 與 Web 和 Azure 儲存體資源進行整合Integrate with web and Azure storage resources
  • 協調涉及多個 Azure 函式的工作流程Orchestrate a workflow involving multiple Azure Functions

規格需求Requirements

練習 1:建立 Azure Functions 專案Exercise 1: Creating an Azure Functions project

  1. 啟動 Visual Studio for MacLaunch Visual Studio for Mac.

  2. 選取 [檔案] > [新增方案]。Select File > New Solution.

  3. 從 [雲端] > [一般] 類別,選取 [Azure Functions] 範本。From the Cloud > General category, select the Azure Functions template. 您將使用 C# 建立 .NET 類別庫來裝載 Azure 函式。You will use C# to create a .NET class library that hosts Azure Functions. 按一下 [下一步] 。Click Next.

    選取 [Azure Functions] 範本

  4. 將 [專案名稱] 設定為 "AzureFunctionsLab" ,然後按一下 [建立]。Set the Project Name to "AzureFunctionsLab" and click Create.

    命名及建立您的 Azure Functions 專案

  5. 展開 [ 方案] 視窗 中的節點。Expand the nodes in the Solution Window. 預設專案範本包含各種 Azure WebJobs 套件及 Newtonsoft.json 套件的 NuGet 參考。The default project template includes NuGet references to a variety of Azure WebJobs packages, as well as the Newtonsoft.Json package.

    另外還有三個檔案: - host.json 用於描述主機的全域組態選項 - local.settings.json 用於進行服務設定。There are also three files: - host.json for describing the global configuration options for the host - local.settings.json for configuring service settings. - 專案範本也會建立預設 HttpTrigger。- The project template also creates a default HttpTrigger. 為了此實驗室,您應該從專案刪除 HttpTrigger.cs 檔案。For the sake of this lab, you should delete the HttpTrigger.cs file from the project.

    開啟 local.settings.jsonOpen local.settings.json. 預設會有兩個空的連接字串設定。It defaults to having two empty connection string settings.

    顯示檔案 local.settings.js的解決方案視窗

練習 2:建立 Azure 儲存體帳戶Exercise 2: Creating an Azure storage account

  1. 登入您的 Azure 帳戶 https://portal.azure.comLog on to your Azure account at https://portal.azure.com.

  2. 在畫面左側的 [我的最愛] 區段下,選取 [儲存體帳戶]:Under the Favorites section, located on the left of the screen, select Storage Accounts :

    Azure 入口網站的 [我的最愛] 區段顯示 [儲存體帳戶] 項目

  3. 選取 [新增] 建立新的儲存體帳戶:Select Add to create a new storage account:

    新增儲存體帳戶的按鈕

  4. 在 [名稱] 中輸入全域唯一名稱,並在 [資源群組] 中重複使用。Enter a globally unique name for the Name and reuse it for the Resource group. 您可以保留所有其他項目的預設值。You can keep all the other items as their default.

    新儲存體帳戶的詳細資料

  5. 按一下 [建立]。Click Create. 建立儲存體帳戶可能需要幾分鐘的時間。It might take a few minutes to create the storage account. 成功建立之後,您會收到通知。You'll get a notification once it has been successfully created.

    部署成功通知

  6. 從 [通知] 選取 [前往資源] 按鈕。Select the Go to resource button from the notification.

  7. 選取 [存取金鑰] 索引標籤。Select the Access keys tab.

    存取金鑰設定

  8. 複製第一個 連接字串Copy the first Connection String. 此字串稍後將用來整合 Azure 儲存體與 Azure Functions。This string is used to integrate Azure storage with your Azure Functions later on.

    金鑰 1 的資訊

  9. 返回 Visual Studio for Mac ,並貼入完整連接字串作為 local.settings.json 中的 AzureWebJobsStorage 設定。Return to Visual Studio for Mac and paste the full connection string in as the AzureWebJobsStorage setting in local.settings.json. 現在您可以參考屬性中的設定名稱,來取得需要存取其資源的函式。Now you can reference the name of the setting in attributes for functions that need access to its resources.

    輸入連接金鑰的本機設定檔案

範例 3:建立及偵錯 Azure 函式Example 3: Creating and debugging an Azure Function

  1. 您現在已準備好開始新增一些程式碼。You're now ready to start adding some code. 使用 .NET 類別庫時,Azure 函式會新增為靜態方法。When working with a .NET class library, Azure Functions are added as static methods. 在 [ 方案] 視窗 中,以滑鼠右鍵按一下 [ AzureFunctions ] 專案節點,然後選取 [ 新增 > 新增函數From the Solution Window , right-click the AzureFunctions project node and select Add > Add Function :

    [新增函式] 選項

  2. 在 [新增 Azure 函式] 對話方塊中,選取 [Generic WebHook] (一般 WebHook) 範本。In the New Azure Functions dialog, select the Generic webhook template. 將 [名稱] 設定為 Add ,然後按一下 [確定] 建立您的函式:Set the Name to Add and click Ok to create your function:

    [新增 Azure 函式] 對話方塊

  3. 在新檔案頂端,新增下列 using 指示詞:At the top of the new file, add the using directives below:

    using Microsoft.Azure.WebJobs.Extensions.Http;
    using System.Web;
    using Microsoft.WindowsAzure.Storage.Table;
    
  4. 移除現有的 Run 方法,然後將下列方法新增至類別作為您的 Azure 函式:Remove the existing Run method and add the method below to the class as your Azure Function:

    [FunctionName("Add")]
    public static int Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]
    HttpRequestMessage req,
    TraceWriter log)
    {
        int x = 1;
        int y = 2;
    
        return x + y;
    }
    
  5. 讓我們逐步解說此方法定義。Let's walk through the method definition piece by piece.

    您首先會看到 FunctionName 屬性將此方法標示為 Azure 函式。The first thing you'll see is the FunctionName attribute that marks this method as an Azure Function. 該屬性會指定函式的公用名稱。The attribute designates the public name of the function. 屬性名稱不一定要與實際方法名稱相符。The attribute name doesn't need to match the actual method name.

    醒目提示 FunctionName 屬性的新 Run 方法

  6. 接下來,將此方法標示為 public static 方法,此為必要。Next, the method is marked as a public static method, which is required. 您也會注意到傳回值是 int 。除非另有使用方法屬性指定,否則 Azure 函數的任何非 void 傳回值都會以文字的形式傳回給用戶端。You'll also notice that the return value is an int. Unless otherwise specified using method attributes, any non-void return value of an Azure Function is returned to the client as text. 根據預設,它會以 XML 傳回,但可變更為 JSON (您將在稍後的實驗室中執行)。By default it's returned as XML , but can be changed to JSON , which you'll do later on in the lab.

    醒目提示初始設定方法的新 Run 方法

  7. 第一個參數以 HttpTrigger 屬性標示,表示此方法是由 HTTP 要求叫用。The first parameter is marked with the HttpTrigger attribute, which indicates that this method is invoked by an HTTP request. 該屬性也會指定方法的授權層級,以及其支援的動詞命令 (在本例中只支援 "GET" )。The attribute also specifies the authorization level of the method, as well as the verbs it supports (only "GET" in this case). 您也可以選擇性地定義 Route 來覆寫方法的路徑,並提供方法來自動從路徑擷取變數。You may also optionally define a Route that overrides the path to the method and offers a way to automatically extract variables from the path. 由於 Route 在這裡為 Null,因此這個方法的路徑將預設為 /api/AddSince the Route is null here, the path to this method will default to /api/Add.

    醒目提示參數的新 Run 方法

  8. 此方法的最後一個參數是 TraceWriter ,可用來記錄診斷和錯誤訊息。The final parameter to the method is a TraceWriter that can be used to log messages for diagnostics and errors.

    醒目提示 TraceWriter 的新 Run 方法

  9. 按一下方法的 return 行邊界,在該行設定中斷點:Set a breakpoint on the return line of the method by clicking in the margin of the line:

    在換行中設定中斷點

  10. F5 鍵或選取 [執行] > [開始偵錯],在偵錯工作階段中建置並執行專案。Build and run the project in a debug session by pressing F5 or selecting Run > Start Debugging. 您也可以按一下 [執行] 按鈕。You could alternatively click the Run button. 這些選項都會執行相同的工作。These options all perform the same task. 此實驗室的其餘部分參考 F5 ,但您可以使用最慣用的方法。The rest of this lab references F5 , but you can use the method you find most comfortable.

    建置並執行專案

  11. 執行專案會自動開啟終端機應用程式。Running the project will automatically open the Terminal application.

  12. 該專案會根據方法屬性及本文稍後將涵蓋的檔案慣例,來偵測 Azure 函式。The project goes through a process of detecting Azure Functions based on method attributes and a file convention that is covered later in this article. 在本例中,它會偵測單一 Azure 函式,並「產生」一個作業函式。In this case, it detects a single Azure Function and "generates" 1 job function.

    終端機中的 Azure 函式輸出

  13. 在啟動訊息底部,Azure Functions 主機會列印任何 HTTP 觸發程序 API 的 URL。At the bottom of the startup messages, the Azure Functions host prints the URLs of any HTTP trigger APIs. 應該只有一個。There should only be one. 複製該 URL,並將它貼到新的瀏覽器索引標籤中。Copy that URL and paste it in a new browser tab.

    Azure 函式 API URL

  14. 此中斷點應該會立即觸發。The breakpoint should trigger immediately. Web 要求已路由傳送至函式,現在可進行偵錯。The web request has been routed to the function and can now be debugged. 將滑鼠移至 x 變數上方以查看其值。Mouse over the x variable to see its value.

    中斷點已觸發

  15. 使用稍早用來新增中斷點的相同方法來移除中斷點 (按一下邊界或選取該行,然後按 F9 鍵)。Remove the breakpoint using the same method used to add it earlier (click on the margin or select the line and press F9 ).

  16. F5 繼續執行。Press F5 to continue running.

  17. 在瀏覽器中,會呈現方法的 XML 結果。In the browser, the XML result of the method will be rendered. 如預期般,硬式編碼的加法運算會產生可能的總和。As expected, the hardcoded addition operation produces a plausible sum. 請注意,如果您在 Safari 中只看到 "3",請移至 [Safari] > [Preferences] (喜好設定) > [Advanced] (進階),然後勾選 [Show Develop menu in menu bar] (在功能表列中顯示開發功能表) 核取方塊並重新載入頁面。Note, if you only see "3" in Safari, go to Safari > Preferences > Advanced and tick the " Show Develop menu in menu bar " checkbox and reload the page.

  18. 在 [Visual Studio for Mac] 中,按一下 [停止] 按鈕以結束偵錯工作階段。In Visual Studio for Mac , click the Stop button to end the debug session. 為了確保套用新的變更,別忘了重新啟動 (停止後再執行) 偵錯工作階段。To ensure that new changes are picked up, don't forget to restart (stop and then run) the debugging session.

    停止偵錯選項

  19. Run 方法中,以下列程式碼取代 xy 定義。In the Run method, replace the x and y definitions with the code below. 此程式碼會從 URL 的查詢字串擷取值,以便能夠動態地根據所提供的參數執行加法運算。This code extracts values from the URL's query string so that the addition operation can be performed dynamically based on the provided parameters.

    var query = HttpUtility.ParseQueryString(req.RequestUri.Query);
    
    int x = int.Parse(query["x"]);
    
    int y = int.Parse(query["y"]);
    
    return x + y;
    
  20. 執行應用程式。Run the application.

  21. 返回瀏覽器視窗,然後將字串 /?x=2&y=3 附加至 URL。Return to the browser window and append the string /?x=2&y=3 to the URL. 整個 URL 現在應該是 http://localhost:7071/api/Add?x=2&y=3The whole URL should now be http://localhost:7071/api/Add?x=2&y=3. 巡覽至新的 URL。Navigate to the new URL.

  22. 此時,結果應該會反映新的參數。This time the result should reflect the new parameters. 您可以隨時使用不同的值來執行專案。Feel free to run the project with different values. 請注意,沒有任何錯誤檢查,因此參數無效或遺失都會擲回錯誤。Note that there isn't any error checking, so invalid or missing parameters will throw an error.

  23. 停止偵錯工作階段。Stop the debugging session.

練習 4:使用 function.jsonExercise 4: Working with function.json

  1. 在先前的練習中提到,Visual Studio for Mac 已為程式庫中定義的 Azure 函式「產生」作業函式。In an earlier exercise, it was mentioned that Visual Studio for Mac "generated" a job function for the Azure Function defined in the library. 這是因為 Azure Functions 不會真的在執行階段使用方法屬性,而是使用編譯時間檔案系統慣例來設定 Azure Functions 可供使用的位置及方式。This is because Azure Functions doesn't actually use the method attributes at runtime, but rather uses a compile-time file system convention to configure where and how Azure Functions are made available. 在 [ 方案] 視窗 中,以滑鼠右鍵按一下您的專案節點,然後選取 [ 在搜尋工具中顯示 ]。From the Solution Window , right-click on your project node and select Reveal in Finder.

    [在尋找工具中顯示] 功能表選項

  2. 向下巡覽檔案系統,直到您抵達 bin/Debug/netstandard2.0Navigate down the file system until you reach bin/Debug/netstandard2.0. 應該會有一個名為 Add 的資料夾。There should be a folder named Add. 此資料夾已建立,並對應至 C# 程式碼中的函式名稱屬性。This folder was created to correspond with the function name attribute in the C# code. 展開 Add 資料夾以顯示單一 function.json 檔案。Expand the Add folder to reveal a single function.json file. 執行階段使用此檔案來裝載及管理 Azure 函式。This file is used by the runtime to host and manage the Azure Function. 對於其他沒有編譯時間支援的語言模型 (例如 C# 指令碼或 JavaScript),則必須手動建立及維護這些資料夾。For other language models without compile-time support (such as C# script or JavaScript), these folders must be manually created and maintained. 對於 C# 開發人員,則會在建置時自動從屬性中繼資料產生這些資料夾。For C# developers, they are automatically generated from attribute metadata upon build. 以滑鼠右鍵按一下 function.json ,然後選擇在 Visual Studio 中開啟。Right-click on function.json and select to open it in Visual Studio.

    檔案目錄中的 function.json

  3. 透過本教學課程的上述步驟,您應該對 C# 屬性有基本的了解。Given the previous steps of this tutorial, you should have a basic understanding of C# attributes. 考慮到這點,此 JSON 看起來應該很熟悉。Taking that into account, this JSON should look familiar. 不過,有些項目並未涵蓋在先前的練習中。However, there are a few items that were not covered in earlier exercises. 例如,每個 繫結 必須已設定其 方向For example, each binding must have its direction set. 您可能猜得到, "in" 表示參數為輸入,而 "out" 表示參數為傳回值 (透過 $return ) 或方法的 out 參數。As you might infer, "in" means that the parameter is input, whereas "out" indicates that the parameter is either a return value (via $return ) or an out parameter to the method. 您也必須指定組件中的 scriptFile (相對於此最終位置) 和 entryPoint 方法 (public static)。You also need to specify the scriptFile (relative to this final location) and the entryPoint method (public and static) within the assembly. 在接下來幾個步驟中,您將使用此模型新增自訂函式路徑,因此請將此檔案內容複製到剪貼簿。In the next few steps you'll add a custom function path using this model, so copy the contents of this file to the clipboard.

    Visual Studio for Mac 中開啟的 function.json 檔案

  4. 在 [ 方案] 視窗 中,以滑鼠右鍵按一下 [ AzureFunctionsLab ] 專案節點,然後選取 [ 加入 > 新資料夾 ]。In the Solution Window , right-click the AzureFunctionsLab project node and select Add > New Folder. 將新的資料夾命名為 AdderName the new folder Adder. 根據預設慣例,此資料夾的名稱會定義 API 的路徑,例如 api/AdderBy default convention, the name of this folder will define the path to the API, such as api/Adder.

    [新增資料夾] 選項

  5. 以滑鼠右鍵按一下 Adder 資料夾,然後選取 [新增] > [新增檔案]。Right-click the Adder folder and select Add > New File.

    [新增檔案] 選項

  6. 選取 [Web] 類別和 [空的 JSON 檔案] 範本。Select the Web category and the Empty JSON File template. 將 [名稱] 設定為 function ,然後按一下 [新增]。Set the Name to function and click New.

    [空的 JSON 檔案] 選項

  7. 貼入其他 function.json 的內容 (來自步驟 3),以取代新建立檔案的預設內容。Paste the contents of the other function.json (from step 3) in to replace the default contents of the newly created file.

  8. 從 JSON 檔案頂端移除下列幾行:Remove the following lines from the top of the json file:

    "configurationSource":"attributes",
    "generatedBy":"Microsoft.NET.Sdk.Functions-1.0.13",
    
  9. 在第一個繫結結尾 ( "name": "req" 行之後),新增下列屬性。At the end of the first binding (after the "name": "req" line), add the properties below. 別忘了在前一行包含逗號。Don't forget to include a comma on the previous line. 此屬性會覆寫預設根目錄,因此它現在會從路徑擷取 int 參數,並放入名為 xy 的方法參數。This property overrides the default root such that it will now extract int parameters from the path and place them into method parameters that are named x and y.

    "direction": "in",
    "route": "Adder/{x:int?}/{y:int?}"
    
  10. 在第一個繫結底下新增另一個繫結。Add another binding underneath the first. 此繫結會處理函式的傳回值。This binding handles the return value of the function. 別忘了在前一行包含逗號:Don't forget to include a comma on the previous line:

    {
    "name": "$return",
    "type": "http",
    "direction": "out"
    }
    
  11. 另請更新檔案底部的 entryPoint 屬性,以使用稱為 "Add2" 的方法,如下所示。Also update the entryPoint property at the bottom of the file to use a method called "Add2" , such as shown below. 這是為了說明路徑 api/Adder... 可對應至任何名稱的適當方法 (此處為 Add2 )。This is to illustrate that the path api/Adder... could map to an appropriate method with any name ( Add2 here).

    "entryPoint": "<project-name>.<function-class-name>.Add2"
    
  12. 您的最終 function.json 檔案看起來應該類似下列 JSON:Your final function.json file should look like the following json:

    {
    "bindings": [
        {
        "type": "httpTrigger",
        "methods": [
            "get"
        ],
        "authLevel": "function",
        "direction": "in",
        "name": "req",
        "route": "Adder/{x:int?}/{y:int?}"
        },
        {
        "name": "$return",
        "type": "http",
        "direction": "out"
        }
    ],
    "disabled": false,
    "scriptFile": "../bin/AzureFunctionsProject.dll",
    "entryPoint": "AzureFunctionsProject.Add.Add2"
    }
    
  13. 完成此工作的最後一個必要步驟,就是指示 Visual Studio for Mac 在每次這個檔案變更時,都將它複製到輸出目錄的同一個相對路徑。The one final step required to make this all work is to instruct Visual Studio for Mac to copy this file to the same relative path in the output directory every time it changes. 選取檔案時,從右側導覽列選擇 [屬性] 索引標籤,然後針對 [複製到輸出目錄] 選取 [有更新時才複製]:With the file selected, choose the properties tab from the right-hand bar, and for Copy to output directory select Copy if newer :

    JSON 檔案的 [屬性] 選項

  14. Add.cs 中,以下列方法取代 Run 方法 (包括屬性) 來完成預期的函式。In Add.cs , replace the Run method (including the attribute) with the following method to fulfill the expected function. 它與 Run 很類似,不同之處在於它未使用任何屬性,而且具有明確參數 xyIt's very similar to Run, except that it uses no attributes and has explicit parameters for x and y.

    public static int Add2(
        HttpRequestMessage req,
        int x,
        int y,
        TraceWriter log)
    {
        return x + y;
    }
    
  15. F5 鍵建置並執行專案。Press F5 to build and run the project.

  16. 當建置完成並啟動平台時,現在會指出要求有第二個可用的路由對應至最近新增的方法:As the build completes and platform spins up, it will now indicate that there is a second route available for requests that maps to the newly added method:

    HTTP 函式的 URL

  17. 返回瀏覽器視窗,並流覽至 http://localhost:7071/api/Adder/3/5Return the browser window and navigate to http://localhost:7071/api/Adder/3/5.

  18. 此時,方法再次有效,可從路徑提取參數並產生總和。This time the method works once again, pulling parameters from the path and producing a sum.

  19. 返回 Visual Studio for Mac 並結束偵錯工作階段。Return to Visual Studio for Mac and end the debugging session.

練習 5:使用 Azure 儲存體資料表Exercise 5: Working with Azure storage tables

通常,您建置的服務可能會比我們目前為止所建置的服務更複雜,而且需要大量時間及/或基礎結構才能執行。Often, the service you build might be much more complex than what we have built so far and require a significant amount of time and/or infrastructure to execute. 在此情況下,您可能會發現將要求排入佇列,再於 Azure Functions 提供支援的資源變成可用時進行處理,是很有效的做法。In that case, you might find it effective to accept requests that are queued for processing when the resources become available, which Azure Functions provides support for. 在其他情況下,您會想要集中儲存資料。In other cases, you’ll want to store data centrally. Azure 儲存體資料表可讓您快速地執行此作業。Azure Storage tables let you do that quickly.

  1. 將下列類別新增至 Add.csAdd the class below to Add.cs. 它應該移至命名空間內,但在現有的類別之外。It should go inside the namespace, but outside the existing class.

    public class TableRow : TableEntity
    {
        public int X { get; set; }
        public int Y { get; set; }
        public int Sum { get; set; }
    }
    
  2. Add 類別內,新增下列程式碼以引進另一個函式。Within the Add class, add the code below to introduce another function. 請注意,此作業是獨特的,到目前為止都未涉及 HTTP 回應。Note that this one is unique so far in that it doesn't involve an HTTP response. 最後一行會傳回新的 TableRow ,並填入可讓您稍後輕鬆擷取的一些重要資訊 ( PartitionKeyRowKey ),以及其參數與總和。The final line returns a new TableRow populated with some key information that will make it easy to retrieve later on ( PartitionKey and RowKey ), as well as its parameters and sum. 方法內的程式碼也會使用 TraceWriter ,讓您更輕鬆地知道函式何時執行。The code within the method also uses the TraceWriter to make it easier to know when the function runs.

    [FunctionName("Process")]
    [return: Table("Results")]
    public static TableRow Process(
        [HttpTrigger(AuthorizationLevel.Function, "get",
            Route = "Process/{x:int}/{y:int}")]
        HttpRequestMessage req,
        int x,
        int y,
        TraceWriter log)
    {
        log.Info($"Processing {x} + {y}");
    
        return new TableRow()
        {
            PartitionKey = "sums",
            RowKey = $"{x}_{y}",
            X = x,
            Y = y,
            Sum = x + y
        };
    }
    
  3. F5 鍵建置並執行專案。Press F5 to build and run the project.

  4. 在 [瀏覽器] 索引標籤中,流覽至 http://localhost:7071/api/Process/4/6In the browser tab, navigate to http://localhost:7071/api/Process/4/6. 這會將另一則訊息放入佇列,最後會導致將另一個資料列新增至資料表。This will put another message into the queue, which should eventually result in another row being added to the table.

  5. 返回 終端機 並留意 4 + 6 的連入要求。Return to Terminal and watch for the incoming request for 4 + 6.

    終端機輸出顯示加法要求

  6. 返回瀏覽器,將要求重新整理為相同的 URL。Return to the browser to refresh the request to the same URL. 此時,您會在 Process 方法之後看到錯誤。This time you'll see an error after the Process method. 這是因為程式碼嘗試使用已存在的分割區和資料列索引鍵組合,將資料列新增至 Azure 資料表儲存體資料表。This is because the code is attempting to add a row to the Azure Table Storage table using a partition and row key combination that already exists.

    System.Private.CoreLib: Exception while executing function: Process. Microsoft.Azure.WebJobs.Host: Error while handling parameter $return after function returned:. Microsoft.Azure.WebJobs.Host: The specified entity already exists.
    
  7. 結束偵錯工作階段。End the debugging session.

  8. 為了減輕錯誤,請將下列參數新增至緊接在 TraceWriter 參數前面的方法定義。To mitigate the error, add the following parameter to the method definition immediately before the TraceWriter parameter. 此參數會指示 Azure Functions 平台從我們用來儲存結果之 PartitionKey 的 [結果] 資料表,嘗試擷取 TableRowThis parameter instructs the Azure Functions platform to attempt to retrieve a TableRow from the Results table on the PartitionKey we've been using to store results. 不過,當您注意到 RowKey 根據相同方法的其他 xy 參數動態產生時,才能體會一些真正的魅力。However, some of the real magic comes into play when you notice that the RowKey is being dynamically generated based on the other x and y parameters for the very same method. 如果該資料列已存在,則 tableRow 會在方法開始時就有該資料列,而不需要開發人員執行額外的工作。If that row already exists, then tableRow will have it when the method begins with no extra work required by the developer. 如果該資料列不存在,則會為 Null。If the row doesn't exist, then it'll just be null. 這類效率可讓開發人員專注於重要的商務邏輯,而不是基礎結構。This sort of efficiency enables developers to focus on the important business logic and not the infrastructure.

    [Table("Results", "sums", "{x}_{y}")]
    TableRow tableRow,
    
  9. 將下列程式碼新增至方法的開頭。Add the code below to the beginning of the method. 如果 tableRow 不是 Null,則我們已有所要求之作業的結果,因此可以立即將它傳回。If tableRow isn't null, then we already have the results for the operation being requested and can return it immediately. 否則,函式會如往常一般繼續執行。Otherwise, the function continues as before. 雖然這可能不是傳回資料的最強固方式,但它指出您只要使用很少的程式碼,就可以在多個可擴充層之間協調非常複雜的作業。While this may not be the most robust way to return the data, it illustrates the point that you can orchestrate incredibly sophisticated operations across multiple scalable tiers with very little code.

    if (tableRow != null)
    {
        log.Info($"{x} + {y} already exists");
        return null;
    }
    
  10. F5 鍵建置並執行專案。Press F5 to build and run the project.

  11. 在 [瀏覽器] 索引標籤中,重新整理 URL http://localhost:7071/api/Process/4/6In the browser tab, refresh the URL at http://localhost:7071/api/Process/4/6. 因為此記錄的資料表資料列存在,所以應該會立即傳回且不會發生錯誤。Since the table row for this record exists, it should return immediately and without error. 由於沒有 HTTP 輸出,您可以在終端機中查看輸出。Since there is no HTTP output, you can see the output in Terminal.

    終端機輸出顯示資料表資料列已存在

  12. 更新 URL 以反映尚未測試的組合(例如) http://localhost:7071/api/Process/5/7Update the URL to reflect a combination not yet tested, such as http://localhost:7071/api/Process/5/7. 注意終端機中的訊息,其指出找不到資料表資料列 (符合預期)。Note the message in Terminal, which indicates that the table row was not found (as expected).

    終端機輸出顯示新的處理序

  13. 返回 Visual Studio for Mac 並結束偵錯工作階段。Return to Visual Studio for Mac and end the debugging session.

總結Summary

在此實驗室中,您已了解如何開始使用 Visual Studio for Mac 建置 Azure 函式。In this lab, you've learned how to get started building Azure Functions with Visual Studio for Mac.