適用於 Azure Functions 的 Microsoft Graph 繫結Microsoft Graph bindings for Azure Functions

這篇文章說明如何在 Azure Functions 中設定並使用 Microsoft Graph 觸發程序和繫結。This article explains how to configure and work with Microsoft Graph triggers and bindings in Azure Functions. 您可以進行這些動作,使用 Azure Functions 來處理來自 Microsoft Graph 的資料、深入資訊和事件。With these, you can use Azure Functions to work with data, insights, and events from the Microsoft Graph.

Microsoft Graph 擴充功能會提供下列繫結:The Microsoft Graph extension provides the following bindings:

這是 Azure Functions 開發人員的參考資訊。This is reference information for Azure Functions developers. 如果您不熟悉 Azure Functions,請從下列資源開始︰If you're new to Azure Functions, start with the following resources:

注意

Microsoft Graph 繫結目前處於 Azure Functions 2.x 版的預覽階段。Microsoft Graph bindings are currently in preview for Azure Functions version 2.x. Functions 1.x 版不加以支援。They are not supported in Functions version 1.x.

封裝Packages

Microsoft.Azure.WebJobs.Extensions.AuthTokens NuGet 套件中提供驗證權杖輸入繫結。The auth token input binding is provided in the Microsoft.Azure.WebJobs.Extensions.AuthTokens NuGet package. Microsoft.Azure.WebJobs.Extensions.MicrosoftGraph 套件中提供其他 Microsoft Graph 繫結。The other Microsoft Graph bindings are provided in the Microsoft.Azure.WebJobs.Extensions.MicrosoftGraph package. 套件的原始程式碼位於 azure-functions-microsoftgraph-extension GitHub 存放庫中。Source code for the packages is in the azure-functions-microsoftgraph-extension GitHub repository.

下表說明如何在每個開發環境中為此繫結新增支援。The following table tells how to add support for this binding in each development environment.

開發環境Development environment 新增支援To add support
本機開發 - C# 類別庫Local development - C# class library 安裝套件Install the package
本機開發 - C# 指令碼、JavaScript、F#、Java 和 PythonLocal development - C# script, JavaScript, F#, Java and Python 註冊擴充功能Register the extension
入口網站開發Portal development 在新增輸出繫結時安裝Install when adding output binding

若要了解如何在不重新發行您的函數應用程式專案的情況下在入口網站中更新現有的繫結延伸模組,請參閱更新您的延伸模組To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

設定擴充功能Setting up the extensions

Microsoft Graph 繫結可透過 繫結擴充功能 提供。Microsoft Graph bindings are available through binding extensions. 繫結擴充功能是 Azure Functions 執行階段的選用元件。Binding extensions are optional components to the Azure Functions runtime. 本節將示範如何設定 Microsoft Graph 和驗證權杖的擴充功能。This section shows how to set up the Microsoft Graph and auth token extensions.

啟用 Functions 2.0 預覽Enabling Functions 2.0 preview

繫結擴充功能僅適用於 Azure Functions 2.0 預覽。Binding extensions are available only for Azure Functions 2.0 preview.

如需如何設定函式應用程式以使用 Functions 執行階段預覽 2.0 版的相關資訊,請參閱如何設定 Azure Functions 執行階段目標版本For information about how to set a function app to use the preview 2.0 version of the Functions runtime, see How to target Azure Functions runtime versions.

安裝擴充功能Installing the extension

若要從 Azure 入口網站安裝擴充功能,請瀏覽至會參考它的範本或繫結。To install an extension from the Azure portal, navigate to either a template or binding that references it. 建立新的函式,並在 [範本選擇] 畫面中選擇 "Microsoft Graph" 情節。Create a new function, and while in the template selection screen, choose the "Microsoft Graph" scenario. 從這個情節選取其中一個範本。Select one of the templates from this scenario. 或者,您可以瀏覽至現有函式的 [整合] 索引標籤,然後選取本文中涵蓋的其中一個繫結。Alternatively, you can navigate to the "Integrate" tab of an existing function and select one of the bindings covered in this article.

在這兩種情況下,會出現警告,指定要安裝的擴充功能。In both cases, a warning will appear which specifies the extension to be installed. 按一下 [安裝] 取得擴充功能。Click Install to obtain the extension. 每個擴充功能只需要針對每個函式應用程式安裝一次。Each extension only needs to be installed once per function app.

注意

入口網站安裝程序在取用方案上可能需要 10 分鐘。The in-portal installation process can take up to 10 minutes on a consumption plan.

如果您使用 Visual Studio,可以安裝本文先前所列的 NuGet 套件來取得擴充功能。If you are using Visual Studio, you can get the extensions by installing the NuGet packages that are listed earlier in this article.

設定驗證/授權Configuring Authentication / Authorization

本文中概述的繫結需要使用身分識別。The bindings outlined in this article require an identity to be used. 這可讓 Microsoft Graph 強制執行權限和稽核互動。This allows the Microsoft Graph to enforce permissions and audit interactions. 識別可以是使用者存取您的應用程式或應用程式本身。The identity can be a user accessing your application or the application itself. 若要設定這個身分識別,請使用 Azure Active Directory 來設定 App Service 驗證/授權To configure this identity, set up App Service Authentication / Authorization with Azure Active Directory. 您也必須要求函式所需的任何資源權限。You will also need to request any resource permissions your functions require.

注意

Microsoft Graph 擴充功能僅支援 Azure AD 驗證。The Microsoft Graph extension only supports Azure AD authentication. 使用者必須使用公司或學校帳戶登入。Users need to log in with a work or school account.

如果您正在使用 Azure 入口網站,您會在安裝擴充功能的提示下方看到警告。If you're using the Azure portal, you'll see a warning below the prompt to install the extension. 警告會提示您設定 App Service 驗證/授權並要求範本或繫結所需的任何權限。The warning prompts you to configure App Service Authentication / Authorization and request any permissions the template or binding requires. 視情況按一下 [立即設定 Azure AD] 或 [立即新增權限]。Click Configure Azure AD now or Add permissions now as appropriate.

驗證權杖Auth token

驗證權杖輸入繫結會取得 Azure AD 指定資源的權杖,並將其提供給您的程式碼作為字串。The auth token input binding gets an Azure AD token for a given resource and provides it to your code as a string. 資源可以是應用程式有權限任何的項目。The resource can be any for which the application has permissions.

本節包含下列小節:This section contains the following subsections:

驗證權杖 - 範例Auth token - example

請參閱特定語言的範例:See the language-specific example:

驗證權杖 - C# 指令碼範例Auth token - C# script example

下列範例可取得使用者設定檔資訊。The following example gets user profile information.

function.json 檔案會使用權杖輸入繫結定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with a token input binding:

{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "type": "token",
      "direction": "in",
      "name": "graphToken",
      "resource": "https://graph.microsoft.com",
      "identity": "userFromRequest"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 指令碼程式碼會使用權杖向 Microsoft Graph 進行 HTTP 呼叫,並傳回結果:The C# script code uses the token to make an HTTP call to the Microsoft Graph and returns the result:

using System.Net; 
using System.Net.Http; 
using System.Net.Http.Headers;
using Microsoft.Extensions.Logging; 

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, string graphToken, ILogger log)
{
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
    return await client.GetAsync("https://graph.microsoft.com/v1.0/me/");
}

驗證權杖 - JavaScript 範例Auth token - JavaScript example

下列範例可取得使用者設定檔資訊。The following example gets user profile information.

function.json 檔案會使用權杖輸入繫結定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with a token input binding:

{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "type": "token",
      "direction": "in",
      "name": "graphToken",
      "resource": "https://graph.microsoft.com",
      "identity": "userFromRequest"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

JavaScript 程式碼會使用權杖向 Microsoft Graph 進行 HTTP 呼叫,並傳回結果。The JavaScript code uses the token to make an HTTP call to the Microsoft Graph and returns the result.

const rp = require('request-promise');

module.exports = function (context, req) {
    let token = "Bearer " + context.bindings.graphToken;

    let options = {
        uri: 'https://graph.microsoft.com/v1.0/me/',
        headers: {
            'Authorization': token
        }
    };
    
    rp(options)
        .then(function(profile) {
            context.res = {
                body: profile
            };
            context.done();
        })
        .catch(function(err) {
            context.res = {
                status: 500,
                body: err
            };
            context.done();
        });
};

驗證權杖 - 屬性Auth token - attributes

C# 類別庫中,使用 Token 屬性。In C# class libraries, use the Token attribute.

驗證權杖 - 設定Auth token - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 Token 屬性。The following table explains the binding configuration properties that you set in the function.json file and the Token attribute.

function.json 屬性function.json property 屬性內容Attribute property 描述Description
namename 必要項目 - 函式程式碼中用於驗證權杖的變數名稱。Required - the variable name used in function code for the auth token. 請參閱從程式碼使用驗證權杖輸入繫結See Using an auth token input binding from code.
typetype 必要項目 - 必須設定為 tokenRequired - must be set to token.
directiondirection 必要項目 - 必須設定為 inRequired - must be set to in.
身分識別identity 身分識別Identity 必要項目 - 要用來執行動作的身分識別。Required - The identity that will be used to perform the action. 可以是下列其中一個值:Can be one of the following values:
  • userFromRequest - 僅在使用 HTTP 觸發程序時才有效。userFromRequest - Only valid with HTTP trigger. 會使用呼叫使用者的身分識別。Uses the identity of the calling user.
  • userFromId - 使用先前已登入之使用者的身分識別與指定的識別碼。userFromId - Uses the identity of a previously logged-in user with the specified ID. 請參閱 userId 屬性。See the userId property.
  • userFromToken - 使用指定權杖所代表的身分識別。userFromToken - Uses the identity represented by the specified token. 請參閱 userToken 屬性。See the userToken property.
  • clientCredentials - 使用函式應用程式的身分識別。clientCredentials - Uses the identity of the function app.
userIduserId UserIdUserId 只有當 identity 設為 userFromId 時才需要。Needed if and only if identity is set to userFromId. 與先前已登入之使用者相關聯的使用者主體識別碼。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 只有當 identity 設為 userFromToken 時才需要。Needed if and only if identity is set to userFromToken. 函式應用程式有效的權杖。A token valid for the function app.
ResourceResource 資源resource 必要項目 - 正在要求權杖的 Azure AD 資源 URL。Required - An Azure AD resource URL for which the token is being requested.

驗證權杖 - 使用方式Auth token - usage

繫結本身不需要任何 Azure AD 權限,但根據使用權杖的方式,您可能必須要求其他權限。The binding itself does not require any Azure AD permissions, but depending on how the token is used, you may need to request additional permissions. 檢查您想要使用權杖存取的資源需求。Check the requirements of the resource you intend to access with the token.

一律會向程式碼顯示權杖作為字串。The token is always presented to code as a string.

注意

在本機使用 userFromIduserFromTokenuserFromRequest 選項進行開發時,您可以手動取得 (英文) 必要的權杖,並指定於呼叫用戶端應用程式的 X-MS-TOKEN-AAD-ID-TOKEN 要求標頭中。When developing locally with either of userFromId, userFromToken or userFromRequest options, required token can be obtained manually and specified in X-MS-TOKEN-AAD-ID-TOKEN request header from a calling client application.

Excel 輸入Excel input

Excel 資料表輸入繫結會讀取儲存在 OneDrive 中 Excel 資料表的內容。The Excel table input binding reads the contents of an Excel table stored in OneDrive.

本節包含下列小節:This section contains the following subsections:

Excel 輸入 - 範例Excel input - example

請參閱特定語言的範例:See the language-specific example:

Excel 輸入 - C# 指令碼範例Excel input - C# script example

下列 function.json 檔案會使用 Excel 輸入繫結定義 HTTP 觸發程序︰The following function.json file defines an HTTP trigger with an Excel input binding:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "type": "excel",
      "direction": "in",
      "name": "excelTableData",
      "path": "{query.workbook}",
      "identity": "UserFromRequest",
      "tableName": "{query.table}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

下列 C# 指令碼程式碼會讀取指定資料表的內容,然後將其傳回給使用者:The following C# script code reads the contents of the specified table and returns them to the user:

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Microsoft.Extensions.Logging;

public static IActionResult Run(HttpRequest req, string[][] excelTableData, ILogger log)
{
    return new OkObjectResult(excelTableData);
}

Excel 輸入 - JavaScript 範例Excel input - JavaScript example

下列 function.json 檔案會使用 Excel 輸入繫結定義 HTTP 觸發程序︰The following function.json file defines an HTTP trigger with an Excel input binding:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "type": "excel",
      "direction": "in",
      "name": "excelTableData",
      "path": "{query.workbook}",
      "identity": "UserFromRequest",
      "tableName": "{query.table}"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

下列 JavaScript 程式碼會讀取指定資料表的內容,然後將其傳回給使用者。The following JavaScript code reads the contents of the specified table and returns them to the user.

module.exports = function (context, req) {
    context.res = {
        body: context.bindings.excelTableData
    };
    context.done();
};

Excel 輸入 - 屬性Excel input - attributes

C# 類別庫中,使用 Excel 屬性。In C# class libraries, use the Excel attribute.

Excel 輸入 - 設定Excel input - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 Excel 屬性。The following table explains the binding configuration properties that you set in the function.json file and the Excel attribute.

function.json 屬性function.json property 屬性內容Attribute property 描述Description
namename 必要項目 - 函式程式碼中用於 Excel 資料表的變數名稱。Required - the variable name used in function code for the Excel table. 請參閱從程式碼使用 Excel 資料表輸入繫結See Using an Excel table input binding from code.
typetype 必要項目 - 必須設定為 excelRequired - must be set to excel.
directiondirection 必要項目 - 必須設定為 inRequired - must be set to in.
身分識別identity 身分識別Identity 必要項目 - 要用來執行動作的身分識別。Required - The identity that will be used to perform the action. 可以是下列其中一個值:Can be one of the following values:
  • userFromRequest - 僅在使用 HTTP 觸發程序時才有效。userFromRequest - Only valid with HTTP trigger. 會使用呼叫使用者的身分識別。Uses the identity of the calling user.
  • userFromId - 使用先前已登入之使用者的身分識別與指定的識別碼。userFromId - Uses the identity of a previously logged-in user with the specified ID. 請參閱 userId 屬性。See the userId property.
  • userFromToken - 使用指定權杖所代表的身分識別。userFromToken - Uses the identity represented by the specified token. 請參閱 userToken 屬性。See the userToken property.
  • clientCredentials - 使用函式應用程式的身分識別。clientCredentials - Uses the identity of the function app.
userIduserId UserIdUserId 只有當 identity 設為 userFromId 時才需要。Needed if and only if identity is set to userFromId. 與先前已登入之使用者相關聯的使用者主體識別碼。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 只有當 identity 設為 userFromToken 時才需要。Needed if and only if identity is set to userFromToken. 函式應用程式有效的權杖。A token valid for the function app.
路徑path 路徑Path 必要項目 - OneDrive 中的 Excel 活頁簿路徑。Required - the path in OneDrive to the Excel workbook.
worksheetNameworksheetName WorksheetNameWorksheetName 資料表所在的工作表。The worksheet in which the table is found.
tableNametableName TableNameTableName 資料表的名稱。The name of the table. 如果未指定,就會使用工作表的內容。If not specified, the contents of the worksheet will be used.

Excel 輸入 - 使用方式Excel input - usage

這個繫結需要下列 Azure AD 權限︰This binding requires the following Azure AD permissions:

資源Resource 權限Permission
Microsoft GraphMicrosoft Graph 讀取使用者檔案Read user files

繫結會向 .NET 函式公開下列類型:The binding exposes the following types to .NET functions:

  • string[][]string[][]
  • Microsoft.Graph.WorkbookTableMicrosoft.Graph.WorkbookTable
  • 自訂物件類型 (使用結構化模型繫結)Custom object types (using structural model binding)

Excel 輸出Excel output

Excel 輸出繫結會修改儲存在 OneDrive 中 Excel 資料表的內容。The Excel output binding modifies the contents of an Excel table stored in OneDrive.

本節包含下列小節:This section contains the following subsections:

Excel 輸出 - 範例Excel output - example

請參閱特定語言的範例:See the language-specific example:

Excel 輸出 - C# 指令碼範例Excel output - C# script example

下列範例會將資料列新增至 Excel 資料表。The following example adds rows to an Excel table.

function.json 檔案會使用 Excel 輸出繫結定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with an Excel output binding:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "newExcelRow",
      "type": "excel",
      "direction": "out",
      "identity": "userFromRequest",
      "updateType": "append",
      "path": "{query.workbook}",
      "tableName": "{query.table}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 指令碼程式碼會以查詢字串的輸入作為基礎,將新的資料列新增至資料表 (假設為單一資料行):The C# script code adds a new row to the table (assumed to be single-column) based on input from the query string:

using System.Net;
using System.Text;
using Microsoft.Extensions.Logging;

public static async Task Run(HttpRequest req, IAsyncCollector<object> newExcelRow, ILogger log)
{
    string input = req.Query
        .FirstOrDefault(q => string.Compare(q.Key, "text", true) == 0)
        .Value;
    await newExcelRow.AddAsync(new {
        Text = input
        // Add other properties for additional columns here
    });
    return;
}

Excel 輸出 - JavaScript 範例Excel output - JavaScript example

下列範例會將資料列新增至 Excel 資料表。The following example adds rows to an Excel table.

function.json 檔案會使用 Excel 輸出繫結定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with an Excel output binding:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "newExcelRow",
      "type": "excel",
      "direction": "out",
      "identity": "userFromRequest",
      "updateType": "append",
      "path": "{query.workbook}",
      "tableName": "{query.table}"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

下列 JavaScript 程式碼會以查詢字串的輸入作為基礎,將新的資料列新增至資料表 (假設為單一資料行)。The following JavaScript code adds a new row to the table (assumed to be single-column) based on input from the query string.

module.exports = function (context, req) {
    context.bindings.newExcelRow = {
        text: req.query.text
        // Add other properties for additional columns here
    }
    context.done();
};

Excel 輸出 - 屬性Excel output - attributes

C# 類別庫中,使用 Excel 屬性。In C# class libraries, use the Excel attribute.

Excel 輸出 - 設定Excel output - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 Excel 屬性。The following table explains the binding configuration properties that you set in the function.json file and the Excel attribute.

function.json 屬性function.json property 屬性內容Attribute property 描述Description
namename 必要項目 - 函式程式碼中用於驗證權杖的變數名稱。Required - the variable name used in function code for the auth token. 請參閱從程式碼使用 Excel 資料表輸出繫結See Using an Excel table output binding from code.
typetype 必要項目 - 必須設定為 excelRequired - must be set to excel.
directiondirection 必要項目 - 必須設定為 outRequired - must be set to out.
身分識別identity 身分識別Identity 必要項目 - 要用來執行動作的身分識別。Required - The identity that will be used to perform the action. 可以是下列其中一個值:Can be one of the following values:
  • userFromRequest - 僅在使用 HTTP 觸發程序時才有效。userFromRequest - Only valid with HTTP trigger. 會使用呼叫使用者的身分識別。Uses the identity of the calling user.
  • userFromId - 使用先前已登入之使用者的身分識別與指定的識別碼。userFromId - Uses the identity of a previously logged-in user with the specified ID. 請參閱 userId 屬性。See the userId property.
  • userFromToken - 使用指定權杖所代表的身分識別。userFromToken - Uses the identity represented by the specified token. 請參閱 userToken 屬性。See the userToken property.
  • clientCredentials - 使用函式應用程式的身分識別。clientCredentials - Uses the identity of the function app.
UserIdUserId userIduserId 只有當 identity 設為 userFromId 時才需要。Needed if and only if identity is set to userFromId. 與先前已登入之使用者相關聯的使用者主體識別碼。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 只有當 identity 設為 userFromToken 時才需要。Needed if and only if identity is set to userFromToken. 函式應用程式有效的權杖。A token valid for the function app.
路徑path 路徑Path 必要項目 - OneDrive 中的 Excel 活頁簿路徑。Required - the path in OneDrive to the Excel workbook.
worksheetNameworksheetName WorksheetNameWorksheetName 資料表所在的工作表。The worksheet in which the table is found.
tableNametableName TableNameTableName 資料表的名稱。The name of the table. 如果未指定,就會使用工作表的內容。If not specified, the contents of the worksheet will be used.
updateTypeupdateType UpdateTypeUpdateType 必要項目 - 要對資料表進行變更的類型。Required - The type of change to make to the table. 可以是下列其中一個值:Can be one of the following values:
  • update - 取代 OneDrive 中的資料表內容。update - Replaces the contents of the table in OneDrive.
  • append - 藉由建立新的資料列,在 OneDrive 中將承載新增至資料表結尾。append - Adds the payload to the end of the table in OneDrive by creating new rows.

Excel 輸出 - 使用方式Excel output - usage

這個繫結需要下列 Azure AD 權限︰This binding requires the following Azure AD permissions:

資源Resource 權限Permission
Microsoft GraphMicrosoft Graph 可以完整存取使用者檔案Have full access to user files

繫結會向 .NET 函式公開下列類型:The binding exposes the following types to .NET functions:

  • string[][]string[][]
  • Newtonsoft.Json.Linq.JObjectNewtonsoft.Json.Linq.JObject
  • Microsoft.Graph.WorkbookTableMicrosoft.Graph.WorkbookTable
  • 自訂物件類型 (使用結構化模型繫結)Custom object types (using structural model binding)

檔案輸入File input

OneDrive 檔案輸入繫結會讀取儲存在 OneDrive 中的檔案內容。The OneDrive File input binding reads the contents of a file stored in OneDrive.

本節包含下列小節:This section contains the following subsections:

檔案輸入 - 範例File input - example

請參閱特定語言的範例:See the language-specific example:

檔案輸入 - C# 指令碼範例File input - C# script example

下列範例會讀取儲存在 OneDrive 中的檔案。The following example reads a file that is stored in OneDrive.

function.json 檔案會使用 OneDrive 檔案輸入繫結定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with a OneDrive file input binding:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "myOneDriveFile",
      "type": "onedrive",
      "direction": "in",
      "path": "{query.filename}",
      "identity": "userFromRequest"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 指令碼程式碼會讀取查詢字串中指定的檔案,並記錄其長度:The C# script code reads the file specified in the query string and logs its length:

using System.Net;
using Microsoft.Extensions.Logging;

public static void Run(HttpRequestMessage req, Stream myOneDriveFile, ILogger log)
{
    log.LogInformation(myOneDriveFile.Length.ToString());
}

檔案輸入 - JavaScript 範例File input - JavaScript example

下列範例會讀取儲存在 OneDrive 中的檔案。The following example reads a file that is stored in OneDrive.

function.json 檔案會使用 OneDrive 檔案輸入繫結定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with a OneDrive file input binding:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "myOneDriveFile",
      "type": "onedrive",
      "direction": "in",
      "path": "{query.filename}",
      "identity": "userFromRequest"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

下列 JavaScript 程式碼會讀取查詢字串中指定的檔案,並傳回其長度。The following JavaScript code reads the file specified in the query string and returns its length.

module.exports = function (context, req) {
    context.res = {
        body: context.bindings.myOneDriveFile.length
    };
    context.done();
};

檔案輸入 - 屬性File input - attributes

C# 類別庫中,使用 OneDrive 屬性。In C# class libraries, use the OneDrive attribute.

檔案輸入 - 設定File input - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 OneDrive 屬性。The following table explains the binding configuration properties that you set in the function.json file and the OneDrive attribute.

function.json 屬性function.json property 屬性內容Attribute property 描述Description
namename 必要項目 - 函式程式碼中用於檔案的變數名稱。Required - the variable name used in function code for the file. 請參閱從程式碼使用 OneDrive 檔案輸入繫結See Using a OneDrive file input binding from code.
typetype 必要項目 - 必須設定為 onedriveRequired - must be set to onedrive.
directiondirection 必要項目 - 必須設定為 inRequired - must be set to in.
身分識別identity 身分識別Identity 必要項目 - 要用來執行動作的身分識別。Required - The identity that will be used to perform the action. 可以是下列其中一個值:Can be one of the following values:
  • userFromRequest - 僅在使用 HTTP 觸發程序時才有效。userFromRequest - Only valid with HTTP trigger. 會使用呼叫使用者的身分識別。Uses the identity of the calling user.
  • userFromId - 使用先前已登入之使用者的身分識別與指定的識別碼。userFromId - Uses the identity of a previously logged-in user with the specified ID. 請參閱 userId 屬性。See the userId property.
  • userFromToken - 使用指定權杖所代表的身分識別。userFromToken - Uses the identity represented by the specified token. 請參閱 userToken 屬性。See the userToken property.
  • clientCredentials - 使用函式應用程式的身分識別。clientCredentials - Uses the identity of the function app.
userIduserId UserIdUserId 只有當 identity 設為 userFromId 時才需要。Needed if and only if identity is set to userFromId. 與先前已登入之使用者相關聯的使用者主體識別碼。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 只有當 identity 設為 userFromToken 時才需要。Needed if and only if identity is set to userFromToken. 函式應用程式有效的權杖。A token valid for the function app.
路徑path 路徑Path 必要項目 - OneDrive 中的檔案路徑。Required - the path in OneDrive to the file.

檔案輸入 - 使用方式File input - usage

這個繫結需要下列 Azure AD 權限︰This binding requires the following Azure AD permissions:

資源Resource 權限Permission
Microsoft GraphMicrosoft Graph 讀取使用者檔案Read user files

繫結會向 .NET 函式公開下列類型:The binding exposes the following types to .NET functions:

  • byte[]byte[]
  • StreamStream
  • 字串string
  • Microsoft.Graph.DriveItemMicrosoft.Graph.DriveItem

檔案輸出File output

OneDrive 檔案輸出繫結會修改儲存在 OneDrive 中的檔案內容。The OneDrive file output binding modifies the contents of a file stored in OneDrive.

本節包含下列小節:This section contains the following subsections:

檔案輸出 - 範例File output - example

請參閱特定語言的範例:See the language-specific example:

檔案輸出 - C# 指令碼範例File output - C# script example

下列範例會寫入儲存在 OneDrive 中的檔案。The following example writes to a file that is stored in OneDrive.

function.json 檔案會使用 OneDrive 輸出繫結定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with a OneDrive output binding:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "myOneDriveFile",
      "type": "onedrive",
      "direction": "out",
      "path": "FunctionsTest.txt",
      "identity": "userFromRequest"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 指令碼程式碼會從查詢字串取得文字,並將它寫入位於呼叫者 OneDrive 的根目錄文字檔 (如先前範例中定義的 FunctionsTest.txt) 中:The C# script code gets text from the query string and writes it to a text file (FunctionsTest.txt as defined in the preceding example) at the root of the caller's OneDrive:

using System.Net;
using System.Text;
using Microsoft.Extensions.Logging;

public static async Task Run(HttpRequest req, ILogger log, Stream myOneDriveFile)
{
    string data = req.Query
        .FirstOrDefault(q => string.Compare(q.Key, "text", true) == 0)
        .Value;
    await myOneDriveFile.WriteAsync(Encoding.UTF8.GetBytes(data), 0, data.Length);
    myOneDriveFile.Close();
    return;
}

檔案輸出 - JavaScript 範例File output - JavaScript example

下列範例會寫入儲存在 OneDrive 中的檔案。The following example writes to a file that is stored in OneDrive.

function.json 檔案會使用 OneDrive 輸出繫結定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with a OneDrive output binding:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "myOneDriveFile",
      "type": "onedrive",
      "direction": "out",
      "path": "FunctionsTest.txt",
      "identity": "userFromRequest"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

JavaScript 程式碼會從查詢字串取得文字,並將它寫入位於呼叫者 OneDrive 的根目錄文字檔 (如上述組態中定義的 FunctionsTest.txt) 中。The JavaScript code gets text from the query string and writes it to a text file (FunctionsTest.txt as defined in the config above) at the root of the caller's OneDrive.

module.exports = function (context, req) {
    context.bindings.myOneDriveFile = req.query.text;
    context.done();
};

檔案輸出 - 屬性File output - attributes

C# 類別庫中,使用 OneDrive 屬性。In C# class libraries, use the OneDrive attribute.

檔案輸出 - 設定File output - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 OneDrive 屬性。The following table explains the binding configuration properties that you set in the function.json file and the OneDrive attribute.

function.json 屬性function.json property 屬性內容Attribute property 描述Description
namename 必要項目 - 函式程式碼中用於檔案的變數名稱。Required - the variable name used in function code for file. 請參閱從程式碼使用 OneDrive 檔案輸出繫結See Using a OneDrive file output binding from code.
typetype 必要項目 - 必須設定為 onedriveRequired - must be set to onedrive.
directiondirection 必要項目 - 必須設定為 outRequired - must be set to out.
身分識別identity 身分識別Identity 必要項目 - 要用來執行動作的身分識別。Required - The identity that will be used to perform the action. 可以是下列其中一個值:Can be one of the following values:
  • userFromRequest - 僅在使用 HTTP 觸發程序時才有效。userFromRequest - Only valid with HTTP trigger. 會使用呼叫使用者的身分識別。Uses the identity of the calling user.
  • userFromId - 使用先前已登入之使用者的身分識別與指定的識別碼。userFromId - Uses the identity of a previously logged-in user with the specified ID. 請參閱 userId 屬性。See the userId property.
  • userFromToken - 使用指定權杖所代表的身分識別。userFromToken - Uses the identity represented by the specified token. 請參閱 userToken 屬性。See the userToken property.
  • clientCredentials - 使用函式應用程式的身分識別。clientCredentials - Uses the identity of the function app.
UserIdUserId userIduserId 只有當 identity 設為 userFromId 時才需要。Needed if and only if identity is set to userFromId. 與先前已登入之使用者相關聯的使用者主體識別碼。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 只有當 identity 設為 userFromToken 時才需要。Needed if and only if identity is set to userFromToken. 函式應用程式有效的權杖。A token valid for the function app.
路徑path 路徑Path 必要項目 - OneDrive 中的檔案路徑。Required - the path in OneDrive to the file.

檔案輸出 - 使用方式File output - usage

這個繫結需要下列 Azure AD 權限︰This binding requires the following Azure AD permissions:

資源Resource 權限Permission
Microsoft GraphMicrosoft Graph 可以完整存取使用者檔案Have full access to user files

繫結會向 .NET 函式公開下列類型:The binding exposes the following types to .NET functions:

  • byte[]byte[]
  • StreamStream
  • 字串string
  • Microsoft.Graph.DriveItemMicrosoft.Graph.DriveItem

Outlook 輸出Outlook output

Outlook 訊息輸出繫結會透過 Outlook 傳送電子郵件訊息。The Outlook message output binding sends a mail message through Outlook.

本節包含下列小節:This section contains the following subsections:

Outlook 輸出 - 範例Outlook output - example

請參閱特定語言的範例:See the language-specific example:

Outlook 輸出 - C# 指令碼範例Outlook output - C# script example

下列範例會透過 Outlook 傳送電子郵件。The following example sends an email through Outlook.

function.json 檔案會使用 Outlook 訊息輸出繫結定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with an Outlook message output binding:

{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "message",
      "type": "outlook",
      "direction": "out",
      "identity": "userFromRequest"
    }
  ],
  "disabled": false
}

C# 指令碼程式碼會從呼叫者將電子郵件傳送至查詢字串中指定的收件者:The C# script code sends a mail from the caller to a recipient specified in the query string:

using System.Net;
using Microsoft.Extensions.Logging;

public static void Run(HttpRequest req, out Message message, ILogger log)
{ 
    string emailAddress = req.Query["to"];
    message = new Message(){
        subject = "Greetings",
        body = "Sent from Azure Functions",
        recipient = new Recipient() {
            address = emailAddress
        }
    };
}

public class Message {
    public String subject {get; set;}
    public String body {get; set;}
    public Recipient recipient {get; set;}
}

public class Recipient {
    public String address {get; set;}
    public String name {get; set;}
}

Outlook 輸出 - JavaScript 範例Outlook output - JavaScript example

下列範例會透過 Outlook 傳送電子郵件。The following example sends an email through Outlook.

function.json 檔案會使用 Outlook 訊息輸出繫結定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with an Outlook message output binding:

{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "message",
      "type": "outlook",
      "direction": "out",
      "identity": "userFromRequest"
    }
  ],
  "disabled": false
}

JavaScript 程式碼會從呼叫者將電子郵件傳送至查詢字串中指定的收件者:The JavaScript code sends a mail from the caller to a recipient specified in the query string:

module.exports = function (context, req) {
    context.bindings.message = {
        subject: "Greetings",
        body: "Sent from Azure Functions with JavaScript",
        recipient: {
            address: req.query.to 
        } 
    };
    context.done();
};

Outlook 輸出 - 屬性Outlook output - attributes

C# 類別庫中,使用 Outlook 屬性。In C# class libraries, use the Outlook attribute.

Outlook 輸出 - 設定Outlook output - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 Outlook 屬性。The following table explains the binding configuration properties that you set in the function.json file and the Outlook attribute.

function.json 屬性function.json property 屬性內容Attribute property 描述Description
namename 必要項目 - 函式程式碼中用於電子郵件訊息的變數名稱。Required - the variable name used in function code for the mail message. 請參閱從程式碼使用 Outlook 訊息輸出繫結See Using an Outlook message output binding from code.
typetype 必要項目 - 必須設定為 outlookRequired - must be set to outlook.
directiondirection 必要項目 - 必須設定為 outRequired - must be set to out.
身分識別identity 身分識別Identity 必要項目 - 要用來執行動作的身分識別。Required - The identity that will be used to perform the action. 可以是下列其中一個值:Can be one of the following values:
  • userFromRequest - 僅在使用 HTTP 觸發程序時才有效。userFromRequest - Only valid with HTTP trigger. 會使用呼叫使用者的身分識別。Uses the identity of the calling user.
  • userFromId - 使用先前已登入之使用者的身分識別與指定的識別碼。userFromId - Uses the identity of a previously logged-in user with the specified ID. 請參閱 userId 屬性。See the userId property.
  • userFromToken - 使用指定權杖所代表的身分識別。userFromToken - Uses the identity represented by the specified token. 請參閱 userToken 屬性。See the userToken property.
  • clientCredentials - 使用函式應用程式的身分識別。clientCredentials - Uses the identity of the function app.
userIduserId UserIdUserId 只有當 identity 設為 userFromId 時才需要。Needed if and only if identity is set to userFromId. 與先前已登入之使用者相關聯的使用者主體識別碼。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 只有當 identity 設為 userFromToken 時才需要。Needed if and only if identity is set to userFromToken. 函式應用程式有效的權杖。A token valid for the function app.

Outlook 輸出 - 使用方式Outlook output - usage

這個繫結需要下列 Azure AD 權限︰This binding requires the following Azure AD permissions:

資源Resource 權限Permission
Microsoft GraphMicrosoft Graph 以使用者的身分傳送電子郵件Send mail as user

繫結會向 .NET 函式公開下列類型:The binding exposes the following types to .NET functions:

  • Microsoft.Graph.MessageMicrosoft.Graph.Message
  • Newtonsoft.Json.Linq.JObjectNewtonsoft.Json.Linq.JObject
  • 字串string
  • 自訂物件類型 (使用結構化模型繫結)Custom object types (using structural model binding)

WebhookWebhooks

Webhook 可讓您回應 Microsoft Graph 中的事件。Webhooks allow you to react to events in the Microsoft Graph. 若要支援 webhook,必須建立函式、重新整理並回應 webhook 訂用帳戶To support webhooks, functions are needed to create, refresh, and react to webhook subscriptions. 完整的 Webhook 解決方案需要下列繫結的組合:A complete webhook solution requires a combination of the following bindings:

繫結本身不需要任何 Azure AD 權限,但您必須要求與所需回應之資源類型相關的權限。The bindings themselves do not require any Azure AD permissions, but you need to request permissions relevant to the resource type you wish to react to. 如需每個資源類型所需權限的清單,請參閱訂用帳戶權限For a list of which permissions are needed for each resource type, see subscription permissions.

如需 Webhook 的詳細資訊,請參閱在 Microsoft Graph 中使用 WebhookFor more information about webhooks, see Working with webhooks in Microsoft Graph.

Webhook 觸發程序Webhook trigger

Microsoft Graph Webhook 觸發程序可讓函式回應從 Microsoft Graph 傳入的 Webhook。The Microsoft Graph webhook trigger allows a function to react to an incoming webhook from the Microsoft Graph. 這個觸發程序的每個執行個體都可回應一種 Microsoft Graph 資源類型。Each instance of this trigger can react to one Microsoft Graph resource type.

本節包含下列小節:This section contains the following subsections:

Webhook 觸發程序 - 範例Webhook trigger - example

請參閱特定語言的範例:See the language-specific example:

Webhook 觸發程序 - C# 指令碼範例Webhook trigger - C# script example

下列範例會處理 Outlook 傳入訊息的 Webhook。The following example handles webhooks for incoming Outlook messages. 若要使用 Webhook 觸發程序,您需要建立訂用帳戶,並可重新整理該訂用帳戶以防止它過期。To use a webhook trigger you create a subscription, and you can refresh the subscription to prevent it from expiring.

function.json 檔案會定義 Webhook 觸發程序:The function.json file defines a webhook trigger:

{
  "bindings": [
    {
      "name": "msg",
      "type": "GraphWebhookTrigger",
      "direction": "in",
      "resourceType": "#Microsoft.Graph.Message"
    }
  ],
  "disabled": false
}

C# 指令碼程式碼會回應傳入的電子郵件訊息,並記錄收件者所傳送及主旨中包含 "Azure Functions" 之電子郵件的內文:The C# script code reacts to incoming mail messages and logs the body of those sent by the recipient and containing "Azure Functions" in the subject:

#r "Microsoft.Graph"
using Microsoft.Graph;
using System.Net;
using Microsoft.Extensions.Logging;

public static async Task Run(Message msg, ILogger log)  
{
    log.LogInformation("Microsoft Graph webhook trigger function processed a request.");

    // Testable by sending oneself an email with the subject "Azure Functions" and some text body
    if (msg.Subject.Contains("Azure Functions") && msg.From.Equals(msg.Sender)) {
        log.LogInformation($"Processed email: {msg.BodyPreview}");
    }
}

Webhook 觸發程序 - JavaScript 範例Webhook trigger - JavaScript example

下列範例會處理 Outlook 傳入訊息的 Webhook。The following example handles webhooks for incoming Outlook messages. 若要使用 Webhook 觸發程序,您需要建立訂用帳戶,並可重新整理該訂用帳戶以防止它過期。To use a webhook trigger you create a subscription, and you can refresh the subscription to prevent it from expiring.

function.json 檔案會定義 Webhook 觸發程序:The function.json file defines a webhook trigger:

{
  "bindings": [
    {
      "name": "msg",
      "type": "GraphWebhookTrigger",
      "direction": "in",
      "resourceType": "#Microsoft.Graph.Message"
    }
  ],
  "disabled": false
}

JavaScript 程式碼會回應傳入的電子郵件訊息,並記錄收件者所傳送及主旨中包含 "Azure Functions" 之電子郵件的內文:The JavaScript code reacts to incoming mail messages and logs the body of those sent by the recipient and containing "Azure Functions" in the subject:

module.exports = function (context) {
    context.log("Microsoft Graph webhook trigger function processed a request.");
    const msg = context.bindings.msg
    // Testable by sending oneself an email with the subject "Azure Functions" and some text body
    if((msg.subject.indexOf("Azure Functions") > -1) && (msg.from === msg.sender) ) {
      context.log(`Processed email: ${msg.bodyPreview}`);
    }
    context.done();
};

Webhook 觸發程序 - 屬性Webhook trigger - attributes

C#類別庫中,使用GraphWebhookTrigger屬性。In C# class libraries, use the GraphWebhookTrigger attribute.

Webhook 觸發程式 - 設定Webhook trigger - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 GraphWebhookTrigger 屬性。The following table explains the binding configuration properties that you set in the function.json file and the GraphWebhookTrigger attribute.

function.json 屬性function.json property 屬性內容Attribute property 描述Description
namename 必要項目 - 函式程式碼中用於電子郵件訊息的變數名稱。Required - the variable name used in function code for the mail message. 請參閱從程式碼使用 Outlook 訊息輸出繫結See Using an Outlook message output binding from code.
typetype 必要項目 - 必須設定為 graphWebhookRequired - must be set to graphWebhook.
directiondirection 必要項目 - 必須設定為 triggerRequired - must be set to trigger.
resourceTyperesourceType ResourceTypeResourceType 必要項目 - 這個函式應回應 webhook 的圖表資源。Required - the graph resource for which this function should respond to webhooks. 可以是下列其中一個值:Can be one of the following values:
  • #Microsoft.Graph.Message - 對 Outlook 訊息所做的變更。#Microsoft.Graph.Message - changes made to Outlook messages.
  • #Microsoft.Graph.DriveItem - 對 OneDrive 根項目所做的變更。#Microsoft.Graph.DriveItem - changes made to OneDrive root items.
  • #Microsoft.Graph.Contact - 對 Outlook 中個人連絡人所做的變更。#Microsoft.Graph.Contact - changes made to personal contacts in Outlook.
  • #Microsoft.Graph.Event - 對 Outlook 行事曆項目所做的變更。#Microsoft.Graph.Event - changes made to Outlook calendar items.

注意

函式應用程式只能有一個針對指定 resourceType 值註冊的函式。A function app can only have one function that is registered against a given resourceType value.

Webhook 觸發程序 - 使用方式Webhook trigger - usage

繫結會向 .NET 函式公開下列類型:The binding exposes the following types to .NET functions:

  • 與資源型別相關的 Microsoft Graph SDK 類型,例如 Microsoft.Graph.MessageMicrosoft.Graph.DriveItemMicrosoft Graph SDK types relevant to the resource type, such as Microsoft.Graph.Message or Microsoft.Graph.DriveItem.
  • 自訂物件類型 (使用結構化模型繫結)Custom object types (using structural model binding)

Webhook 輸入Webhook input

Microsoft Graph Webhook 輸入繫結可讓您擷取由此函式應用程式管理的訂用帳戶清單。The Microsoft Graph webhook input binding allows you to retrieve the list of subscriptions managed by this function app. 繫結會讀取自函式應用程式儲存體,因此不會反映從應用程式外部建立的其他訂用帳戶。The binding reads from function app storage, so it does not reflect other subscriptions created from outside the app.

本節包含下列小節:This section contains the following subsections:

Webhook 輸入 - 範例Webhook input - example

請參閱特定語言的範例:See the language-specific example:

Webhook 輸入 - C# 指令碼範例Webhook input - C# script example

下列範例會取得呼叫使用者的所有訂用帳戶,並加以刪除。The following example gets all subscriptions for the calling user and deletes them.

function.json 檔案會透過訂用帳戶輸入繫結以及使用刪除動作的訂用帳戶輸出繫結,來定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with a subscription input binding and a subscription output binding that uses the delete action:

{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "existingSubscriptions",
      "direction": "in",
      "filter": "userFromRequest"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "subscriptionsToDelete",
      "direction": "out",
      "action": "delete",
      "identity": "userFromRequest"
    },
    {
      "type": "http",
      "name": "res",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 指令碼程式碼會取得訂用帳戶,並加以刪除:The C# script code gets the subscriptions and deletes them:

using System.Net;
using Microsoft.Extensions.Logging;

public static async Task Run(HttpRequest req, string[] existingSubscriptions, IAsyncCollector<string> subscriptionsToDelete, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    foreach (var subscription in existingSubscriptions)
    {
        log.LogInformation($"Deleting subscription {subscription}");
        await subscriptionsToDelete.AddAsync(subscription);
    }
}

Webhook 輸入 - JavaScript 範例Webhook input - JavaScript example

下列範例會取得呼叫使用者的所有訂用帳戶,並加以刪除。The following example gets all subscriptions for the calling user and deletes them.

function.json 檔案會透過訂用帳戶輸入繫結以及使用刪除動作的訂用帳戶輸出繫結,來定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with a subscription input binding and a subscription output binding that uses the delete action:

{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "existingSubscriptions",
      "direction": "in",
      "filter": "userFromRequest"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "subscriptionsToDelete",
      "direction": "out",
      "action": "delete",
      "identity": "userFromRequest"
    },
    {
      "type": "http",
      "name": "res",
      "direction": "out"
    }
  ],
  "disabled": false
}

JavaScript 程式碼會取得訂用帳戶,並加以刪除:The JavaScript code gets the subscriptions and deletes them:

module.exports = function (context, req) {
    const existing = context.bindings.existingSubscriptions;
    var toDelete = [];
    for (var i = 0; i < existing.length; i++) {
        context.log(`Deleting subscription ${existing[i]}`);
        todelete.push(existing[i]);
    }
    context.bindings.subscriptionsToDelete = toDelete;
    context.done();
};

Webhook 輸入 - 屬性Webhook input - attributes

C#類別庫中,使用GraphWebhookSubscription屬性。In C# class libraries, use the GraphWebhookSubscription attribute.

Webhook 輸入 - 設定Webhook input - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 GraphWebhookSubscription 屬性。The following table explains the binding configuration properties that you set in the function.json file and the GraphWebhookSubscription attribute.

function.json 屬性function.json property 屬性內容Attribute property 描述Description
namename 必要項目 - 函式程式碼中用於電子郵件訊息的變數名稱。Required - the variable name used in function code for the mail message. 請參閱從程式碼使用 Outlook 訊息輸出繫結See Using an Outlook message output binding from code.
typetype 必要項目 - 必須設定為 graphWebhookSubscriptionRequired - must be set to graphWebhookSubscription.
directiondirection 必要項目 - 必須設定為 inRequired - must be set to in.
filterfilter FilterFilter 如果設定為 userFromRequest,繫結就只會擷取呼叫使用者擁有的訂用帳戶 (僅在搭配 HTTP 觸發程序時有效)。If set to userFromRequest, then the binding will only retrieve subscriptions owned by the calling user (valid only with HTTP trigger).

Webhook 輸入 - 使用方式Webhook input - usage

繫結會向 .NET 函式公開下列類型:The binding exposes the following types to .NET functions:

  • string[]string[]
  • 自訂物件類型陣列Custom object type arrays
  • Newtonsoft.Json.Linq.JObject[]Newtonsoft.Json.Linq.JObject[]
  • Microsoft.Graph.Subscription[]Microsoft.Graph.Subscription[]

Webhook 輸出Webhook output

Webhook 訂用帳戶輸出繫結可讓您建立、刪除和重新整理 Microsoft Graph 中的 Webhook 訂用帳戶。The webhook subscription output binding allows you to create, delete, and refresh webhook subscriptions in the Microsoft Graph.

本節包含下列小節:This section contains the following subsections:

Webhook 輸出 - 範例Webhook output - example

請參閱特定語言的範例:See the language-specific example:

Webhook 輸出 - C# 指令碼範例Webhook output - C# script example

下列範例會建立訂用帳戶。The following example creates a subscription. 您可以重新整理訂用帳戶以防止訂用帳戶過期。You can refresh the subscription to prevent it from expiring.

function.json 檔案會使用建立動作,利用訂用帳戶輸出繫結來定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with a subscription output binding using the create action:

{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "clientState",
      "direction": "out",
      "action": "create",
      "subscriptionResource": "me/mailFolders('Inbox')/messages",
      "changeTypes": [
        "created"
      ],
      "identity": "userFromRequest"
    },
    {
      "type": "http",
      "name": "$return",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 指令碼程式碼會註冊 Webhook,當呼叫使用者收到 Outlook 訊息時會通知此函式應用程式:The C# script code registers a webhook that will notify this function app when the calling user receives an Outlook message:

using System;
using System.Net;
using Microsoft.Extensions.Logging;

public static HttpResponseMessage run(HttpRequestMessage req, out string clientState, ILogger log)
{
  log.LogInformation("C# HTTP trigger function processed a request.");
    clientState = Guid.NewGuid().ToString();
    return new HttpResponseMessage(HttpStatusCode.OK);
}

Webhook 輸出 - JavaScript 範例Webhook output - JavaScript example

下列範例會建立訂用帳戶。The following example creates a subscription. 您可以重新整理訂用帳戶以防止訂用帳戶過期。You can refresh the subscription to prevent it from expiring.

function.json 檔案會使用建立動作,利用訂用帳戶輸出繫結來定義 HTTP 觸發程序︰The function.json file defines an HTTP trigger with a subscription output binding using the create action:

{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "clientState",
      "direction": "out",
      "action": "create",
      "subscriptionResource": "me/mailFolders('Inbox')/messages",
      "changeTypes": [
        "created"
      ],
      "identity": "userFromRequest"
    },
    {
      "type": "http",
      "name": "$return",
      "direction": "out"
    }
  ],
  "disabled": false
}

JavaScript 程式碼會註冊 Webhook,當呼叫使用者收到 Outlook 訊息時會通知此函式應用程式:The JavaScript code registers a webhook that will notify this function app when the calling user receives an Outlook message:

const uuidv4 = require('uuid/v4');

module.exports = function (context, req) {
    context.bindings.clientState = uuidv4();
    context.done();
};

Webhook 輸出 - 屬性Webhook output - attributes

C#類別庫中,使用GraphWebhookSubscription屬性。In C# class libraries, use the GraphWebhookSubscription attribute.

Webhook 輸出 - 設定Webhook output - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 GraphWebhookSubscription 屬性。The following table explains the binding configuration properties that you set in the function.json file and the GraphWebhookSubscription attribute.

function.json 屬性function.json property 屬性內容Attribute property 描述Description
namename 必要項目 - 函式程式碼中用於電子郵件訊息的變數名稱。Required - the variable name used in function code for the mail message. 請參閱從程式碼使用 Outlook 訊息輸出繫結See Using an Outlook message output binding from code.
typetype 必要項目 - 必須設定為 graphWebhookSubscriptionRequired - must be set to graphWebhookSubscription.
directiondirection 必要項目 - 必須設定為 outRequired - must be set to out.
身分識別identity 身分識別Identity 必要項目 - 要用來執行動作的身分識別。Required - The identity that will be used to perform the action. 可以是下列其中一個值:Can be one of the following values:
  • userFromRequest - 僅在使用 HTTP 觸發程序時才有效。userFromRequest - Only valid with HTTP trigger. 會使用呼叫使用者的身分識別。Uses the identity of the calling user.
  • userFromId - 使用先前已登入之使用者的身分識別與指定的識別碼。userFromId - Uses the identity of a previously logged-in user with the specified ID. 請參閱 userId 屬性。See the userId property.
  • userFromToken - 使用指定權杖所代表的身分識別。userFromToken - Uses the identity represented by the specified token. 請參閱 userToken 屬性。See the userToken property.
  • clientCredentials - 使用函式應用程式的身分識別。clientCredentials - Uses the identity of the function app.
userIduserId UserIdUserId 只有當 identity 設為 userFromId 時才需要。Needed if and only if identity is set to userFromId. 與先前已登入之使用者相關聯的使用者主體識別碼。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 只有當 identity 設為 userFromToken 時才需要。Needed if and only if identity is set to userFromToken. 函式應用程式有效的權杖。A token valid for the function app.
actionaction ActionAction 必要項目 - 指定繫結應該要執行的動作。Required - specifies the action the binding should perform. 可以是下列其中一個值:Can be one of the following values:
  • create - 註冊新的訂用帳戶。create - Registers a new subscription.
  • delete - 刪除指定的訂用帳戶。delete - Deletes a specified subscription.
  • refresh - 重新整理指定的訂用帳戶以避免過期。refresh - Refreshes a specified subscription to keep it from expiring.
subscriptionResourcesubscriptionResource SubscriptionResourceSubscriptionResource 只有當_動作_設為 create 時才需要。Needed if and only if the action is set to create. 指定要監視以進行變更的 Microsoft Graph 資源。Specifies the Microsoft Graph resource that will be monitored for changes. 請參閱在 Microsoft Graph 中使用 webhookSee Working with webhooks in Microsoft Graph.
changeTypechangeType ChangeTypeChangeType 只有當_動作_設為 create 時才需要。Needed if and only if the action is set to create. 指出會引發通知之訂閱資源中的變更類型。Indicates the type of change in the subscribed resource that will raise a notification. 支援的值為:createdupdateddeletedThe supported values are: created, updated, deleted. 可以使用逗號分隔清單來組合多個值。Multiple values can be combined using a comma-separated list.

Webhook 輸出 - 使用方式Webhook output - usage

繫結會向 .NET 函式公開下列類型:The binding exposes the following types to .NET functions:

  • 字串string
  • Microsoft.Graph.SubscriptionMicrosoft.Graph.Subscription

Webhook 訂用帳戶重新整理Webhook subscription refresh

有兩種方法可重新整理訂用帳戶:There are two approaches to refreshing subscriptions:

  • 使用應用程式識別碼來處理所有訂用帳戶。Use the application identity to deal with all subscriptions. 這將需要 Azure Active Directory 系統管理員同意。Azure Functions 支援的所有語言都可以使用此方法。This will require consent from an Azure Active Directory admin. This can be used by all languages supported by Azure Functions.
  • 使用與每個訂用帳戶相關聯的身分識別,方法是手動繫結每個使用者識別碼。Use the identity associated with each subscription by manually binding each user ID. 這將需要一些自訂程式碼來執行繫結。This will require some custom code to perform the binding. 只有 .NET 函式才能使用。This can only be used by .NET functions.

本節包含下列各種方法的範例:This section contains an example for each of these approaches:

Webhook 訂用帳戶重新整理 - 應用程式身分識別範例Webhook Subscription refresh - app identity example

請參閱特定語言的範例:See the language-specific example:

應用程式身分識別重新整理 - C# 指令碼範例App identity refresh - C# script example

下列範例會使用應用程式識別碼來重新整理訂用帳戶。The following example uses the application identity to refresh a subscription.

function.json 會使用訂用帳戶輸入繫結和訂用帳戶輸出繫結來定義計時器觸發程序:The function.json defines a timer trigger with a subscription input binding and a subscription output binding:

{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 * * */2 * *"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "existingSubscriptions",
      "direction": "in"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "subscriptionsToRefresh",
      "direction": "out",
      "action": "refresh",
      "identity": "clientCredentials"
    }
  ],
  "disabled": false
}

C# 指令碼程式碼會重新整理訂用帳戶:The C# script code refreshes the subscriptions:

using System;
using Microsoft.Extensions.Logging;

public static void Run(TimerInfo myTimer, string[] existingSubscriptions, ICollector<string> subscriptionsToRefresh, ILogger log)
{
    // This template uses application permissions and requires consent from an Azure Active Directory admin.
    // See https://go.microsoft.com/fwlink/?linkid=858780
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    foreach (var subscription in existingSubscriptions)
    {
      log.LogInformation($"Refreshing subscription {subscription}");
      subscriptionsToRefresh.Add(subscription);
    }
}

應用程式身分識別重新整理 - C# 指令碼範例App identity refresh - C# script example

下列範例會使用應用程式識別碼來重新整理訂用帳戶。The following example uses the application identity to refresh a subscription.

function.json 會使用訂用帳戶輸入繫結和訂用帳戶輸出繫結來定義計時器觸發程序:The function.json defines a timer trigger with a subscription input binding and a subscription output binding:

{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 * * */2 * *"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "existingSubscriptions",
      "direction": "in"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "subscriptionsToRefresh",
      "direction": "out",
      "action": "refresh",
      "identity": "clientCredentials"
    }
  ],
  "disabled": false
}

JavaScript 程式碼會重新整理訂用帳戶:The JavaScript code refreshes the subscriptions:

// This template uses application permissions and requires consent from an Azure Active Directory admin.
// See https://go.microsoft.com/fwlink/?linkid=858780

module.exports = function (context) {
    const existing = context.bindings.existingSubscriptions;
    var toRefresh = [];
    for (var i = 0; i < existing.length; i++) {
        context.log(`Refreshing subscription ${existing[i]}`);
        toRefresh.push(existing[i]);
    }
    context.bindings.subscriptionsToRefresh = toRefresh;
    context.done();
};

Webhook 訂用帳戶重新整理 - 使用者身分識別範例Webhook Subscription refresh - user identity example

下列範例會使用使用者身分識別來重新整理訂用帳戶。The following example uses the user identity to refresh a subscription.

function.json 檔案會定義計時器觸發程序,並將訂用帳戶輸入繫結延遲至函式程式碼:The function.json file defines a timer trigger and defers the subscription input binding to the function code:

{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 * * */2 * *"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "existingSubscriptions",
      "direction": "in"
    }
  ],
  "disabled": false
}

C# 指令碼程式碼會重新整理訂用帳戶,並在程式碼中使用每個使用者的身分識別建立輸出繫結:The C# script code refreshes the subscriptions and creates the output binding in code, using each user's identity:

using System;
using Microsoft.Extensions.Logging;

public static async Task Run(TimerInfo myTimer, UserSubscription[] existingSubscriptions, IBinder binder, ILogger log)
{
  log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    foreach (var subscription in existingSubscriptions)
    {
        // binding in code to allow dynamic identity
        using (var subscriptionsToRefresh = await binder.BindAsync<IAsyncCollector<string>>(
            new GraphWebhookSubscriptionAttribute() {
                Action = "refresh",
                Identity = "userFromId",
                UserId = subscription.UserId
            }
        ))
        {
            log.LogInformation($"Refreshing subscription {subscription}");
            await subscriptionsToRefresh.AddAsync(subscription);
        }

    }
}

public class UserSubscription {
    public string UserId {get; set;}
    public string Id {get; set;}
}

後續步驟Next steps