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:

备注

Azure Functions 2.x 版及更高版本的 Microsoft Graph 绑定目前处于预览状态。Microsoft Graph bindings are currently in preview for Azure Functions version 2.x and higher. 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.

使用以下方法在首选开发环境中添加支持。Add support in you preferred development environment using the following methods.

开发环境Development environment 应用程序类型Application type 添加支持To add support
Visual StudioVisual Studio C# 类库C# class library 安装 NuGet 包Install the NuGet package
Visual Studio CodeVisual Studio Code 基于核心工具Based on core tools 注册扩展捆绑包Register the extension bundle

建议安装 Azure Tools 扩展Installing the Azure Tools extension is recommended.
任何其他编辑器/IDEAny other editor/IDE 基于核心工具Based on core tools 注册扩展捆绑包Register the extension bundle
Azure 门户Azure Portal 仅在门户中联机Online only in portal 在添加绑定时安装Installs when adding a binding

请参阅更新扩展以更新现有绑定扩展,而无需重新发布函数应用。See Update your extensions to update existing binding extensions without having to republish your function app.

设置扩展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.0Enabling Functions 2.0

绑定扩展仅适用于 Azure Functions 2.0。Binding extensions are available only for Azure Functions 2.0.

有关如何将函数应用设置为使用 2.0 版的 Functions 运行时的信息,请参阅如何面向 Azure Functions 运行时版本For information about how to set a function app to use the 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 设置应用服务身份验证/授权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. 该警告提示配置应用服务身份验证/授权并请求模板或绑定所需的任意权限。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://microsoftgraph.chinacloudapi.cn",
      "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://microsoftgraph.chinacloudapi.cn/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://microsoftgraph.chinacloudapi.cn",
      "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://microsoftgraph.chinacloudapi.cn/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 属性Attribute property 说明Description
namename 不适用n/a 必需 - 在身份验证令牌的函数代码中使用的变量名称。Required - the variable name used in function code for the auth token. 请参阅在代码中使用身份验证令牌输入绑定See Using an auth token input binding from code.
typetype 不适用n/a 必需 - 必须设置为 tokenRequired - must be set to token.
directiondirection 不适用n/a 必需 - 必须设置为 inRequired - must be set to in.
identityidentity 标识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 - 使用具有指定 ID 的已登录用户的标识。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 设置为 时为必需userFromIdNeeded if and only if identity is set to userFromId. 与已登录用户关联的用户主体 ID。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 仅在将 identity 设置为 时为必需userFromTokenNeeded if and only if identity is set to userFromToken. 函数应用的有效令牌。A token valid for the function app.
资源Resource resourceresource 必需 - 正在为其请求令牌的 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 属性Attribute property 说明Description
namename 不适用n/a 必需 - 在 Excel 表的函数代码中使用的变量名称。Required - the variable name used in function code for the Excel table. 请参阅在代码中使用 Excel 表输入绑定See Using an Excel table input binding from code.
typetype 不适用n/a 必需 - 必须设置为 excelRequired - must be set to excel.
directiondirection 不适用n/a 必需 - 必须设置为 inRequired - must be set to in.
identityidentity 标识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 - 使用具有指定 ID 的已登录用户的标识。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 设置为 时为必需userFromIdNeeded if and only if identity is set to userFromId. 与已登录用户关联的用户主体 ID。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 仅在将 identity 设置为 时为必需userFromTokenNeeded 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 属性Attribute property 说明Description
namename 不适用n/a 必需 - 在身份验证令牌的函数代码中使用的变量名称。Required - the variable name used in function code for the auth token. 请参阅在代码中使用 Excel 表输出绑定See Using an Excel table output binding from code.
typetype 不适用n/a 必需 - 必须设置为 excelRequired - must be set to excel.
directiondirection 不适用n/a 必需 - 必须设置为 outRequired - must be set to out.
identityidentity 标识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 - 使用具有指定 ID 的已登录用户的标识。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 设置为 时为必需userFromIdNeeded if and only if identity is set to userFromId. 与已登录用户关联的用户主体 ID。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 仅在将 identity 设置为 时为必需userFromTokenNeeded 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 属性Attribute property 说明Description
namename 不适用n/a 必需 - 在文件的函数代码中使用的变量名称。Required - the variable name used in function code for the file. 请参阅在代码中使用 OneDrive 文件输入绑定See Using a OneDrive file input binding from code.
typetype 不适用n/a 必需 - 必须设置为 onedriveRequired - must be set to onedrive.
directiondirection 不适用n/a 必需 - 必须设置为 inRequired - must be set to in.
identityidentity 标识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 - 使用具有指定 ID 的已登录用户的标识。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 设置为 时为必需userFromIdNeeded if and only if identity is set to userFromId. 与已登录用户关联的用户主体 ID。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 仅在将 identity 设置为 时为必需userFromTokenNeeded 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
  • stringstring
  • 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# 脚本代码从查询字符串获取文本并将其写入文本文件(上述示例中定义的 FunctionsTest.txt,位于调用者的 OneDrive 的根目录):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 代码从查询字符串获取文本并将其写入文本文件(上述配置中定义的 FunctionsTest.txt,位于调用者的 OneDrive 的根目录)。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 属性Attribute property 说明Description
namename 不适用n/a 必需 - 在文件的函数代码中使用的变量名称。Required - the variable name used in function code for file. 请参阅在代码中使用 OneDrive 文件输出绑定See Using a OneDrive file output binding from code.
typetype 不适用n/a 必需 - 必须设置为 onedriveRequired - must be set to onedrive.
directiondirection 不适用n/a 必需 - 必须设置为 outRequired - must be set to out.
identityidentity 标识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 - 使用具有指定 ID 的已登录用户的标识。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 设置为 时为必需userFromIdNeeded if and only if identity is set to userFromId. 与已登录用户关联的用户主体 ID。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 仅在将 identity 设置为 时为必需userFromTokenNeeded 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
  • stringstring
  • 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 属性Attribute property 说明Description
namename 不适用n/a 必需 - 在邮件的函数代码中使用的变量名称。Required - the variable name used in function code for the mail message. 请参阅在代码中使用 Outlook 邮件输出绑定See Using an Outlook message output binding from code.
typetype 不适用n/a 必需 - 必须设置为 outlookRequired - must be set to outlook.
directiondirection 不适用n/a 必需 - 必须设置为 outRequired - must be set to out.
identityidentity 标识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 - 使用具有指定 ID 的已登录用户的标识。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 设置为 时为必需userFromIdNeeded if and only if identity is set to userFromId. 与已登录用户关联的用户主体 ID。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 仅在将 identity 设置为 时为必需userFromTokenNeeded 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
  • stringstring
  • 自定义对象类型(使用结构化模型绑定)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 属性Attribute property 说明Description
namename 不适用n/a 必需 - 在邮件的函数代码中使用的变量名称。Required - the variable name used in function code for the mail message. 请参阅在代码中使用 Outlook 邮件输出绑定See Using an Outlook message output binding from code.
typetype 不适用n/a 必需 - 必须设置为 graphWebhookRequired - must be set to graphWebhook.
directiondirection 不适用n/a 必需 - 必须设置为 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 属性Attribute property 说明Description
namename 不适用n/a 必需 - 在邮件的函数代码中使用的变量名称。Required - the variable name used in function code for the mail message. 请参阅在代码中使用 Outlook 邮件输出绑定See Using an Outlook message output binding from code.
typetype 不适用n/a 必需 - 必须设置为 graphWebhookSubscriptionRequired - must be set to graphWebhookSubscription.
directiondirection 不适用n/a 必需 - 必须设置为 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 属性Attribute property 说明Description
namename 不适用n/a 必需 - 在邮件的函数代码中使用的变量名称。Required - the variable name used in function code for the mail message. 请参阅在代码中使用 Outlook 邮件输出绑定See Using an Outlook message output binding from code.
typetype 不适用n/a 必需 - 必须设置为 graphWebhookSubscriptionRequired - must be set to graphWebhookSubscription.
directiondirection 不适用n/a 必需 - 必须设置为 outRequired - must be set to out.
identityidentity 标识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 - 使用具有指定 ID 的已登录用户的标识。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 设置为 时为必需userFromIdNeeded if and only if identity is set to userFromId. 与已登录用户关联的用户主体 ID。A user principal ID associated with a previously logged-in user.
userTokenuserToken UserTokenUserToken 仅在将 identity 设置为 时为必需userFromTokenNeeded if and only if identity is set to userFromToken. 函数应用的有效令牌。A token valid for the function app.
actionaction 操作Action 必需 - 指定绑定应执行的操作。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 仅在将 action 设置为 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 仅在将 action 设置为 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:

  • stringstring
  • 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.
  • 通过手动绑定各个用户 ID 来使用与各个订阅关联的标识。Use the identity associated with each subscription by manually binding each user ID. 此方法需要一些自定义代码来执行绑定。This will require some custom code to perform the binding. 仅 .NET functions 可以使用此方法。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