Azure Functions HTTP 触发器Azure Functions HTTP trigger

借助 HTTP 触发器,可以使用 HTTP 请求调用函数。The HTTP trigger lets you invoke a function with an HTTP request. 可以使用 HTTP 触发器生成无服务器 API 和响应 Webhook。You can use an HTTP trigger to build serverless APIs and respond to webhooks.

HTTP 触发函数的默认返回值如下:The default return value for an HTTP-triggered function is:

  • HTTP 204 No Content,在 Functions 2.x 及更高版本中为空主体HTTP 204 No Content with an empty body in Functions 2.x and higher
  • HTTP 200 OK,在 Functions 1.x 中为空主体HTTP 200 OK with an empty body in Functions 1.x

若要修改 HTTP 响应,请配置输出绑定To modify the HTTP response, configure an output binding.

有关 HTTP 绑定的详细信息,请参阅概述输出绑定参考For more information about HTTP bindings, see the overview and output binding reference.


如果计划使用 HTTP 或 WebHook 绑定,请制定计划来避免因实例化 HttpClient 不当导致的端口耗尽现象。If you plan to use the HTTP or WebHook bindings, plan to avoid port exhaustion that can be caused by improper instantiation of HttpClient. 有关详细信息,请参阅如何在 Azure Functions 中管理连接For more information, see How to manage connections in Azure Functions.


以下示例显示一个在查询字符串或 HTTP 请求正文中查找 name 参数的 C# 函数The following example shows a C# function that looks for a name parameter either in the query string or the body of the HTTP request. 请注意,返回值用于输出绑定,但不需要返回值属性。Notice that the return value is used for the output binding, but a return value attribute isn't required.

public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
    HttpRequest req, ILogger log)
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];
    string requestBody = String.Empty;
    using (StreamReader streamReader =  new  StreamReader(req.Body))
        requestBody = await streamReader.ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;
    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");

特性和注释Attributes and annotations

C# 类库和 Java 中,HttpTrigger 特性可用于配置函数。In C# class libraries and Java, the HttpTrigger attribute is available to configure the function.

可以在特性构造函数参数、Webhook 类型与路由模板中设置授权级别和允许的 HTTP 方法。You can set the authorization level and allowable HTTP methods in attribute constructor parameters, webhook type, and a route template. 有关这些设置的详细信息,请参阅配置For more information about these settings, see configuration.

此示例演示如何使用 HttpTrigger 特性。This example demonstrates how to use the HttpTrigger attribute.

public static Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req)

有关完整示例,请参阅触发器示例For a complete example, see the trigger example.


下表解释了在 function.json 文件和 HttpTrigger 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the HttpTrigger attribute.

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 不适用n/a 必需 - 必须设置为 httpTriggerRequired - must be set to httpTrigger.
directiondirection 不适用n/a 必需 - 必须设置为 inRequired - must be set to in.
namename 不适用n/a 必需 - 在请求或请求正文的函数代码中使用的变量名称。Required - the variable name used in function code for the request or request body.
authLevelauthLevel AuthLevelAuthLevel 确定请求中需要提供的密钥(如果有),以便调用此函数。Determines what keys, if any, need to be present on the request in order to invoke the function. 授权级别可以是以下值之一:The authorization level can be one of the following values:
  • anonymous—无需 API 密钥。anonymous—No API key is required.
  • function—特定于函数的 API 密钥是必需的。function—A function-specific API key is required. 如果未提供任何值,该值为默认值。This is the default value if none is provided.
  • admin—无需主密钥。admin—The master key is required.
有关详细信息,请参阅有关授权密钥的部分。For more information, see the section about authorization keys.
methodsmethods 方法Methods HTTP 方法的数组,该函数将响应此方法。An array of the HTTP methods to which the function responds. 如果未指定,该函数将响应所有 HTTP 方法。If not specified, the function responds to all HTTP methods. 请参阅自定义 HTTP 终结点See customize the HTTP endpoint.
routeroute RouteRoute 定义路由模板,控制函数将响应的请求 URL。Defines the route template, controlling to which request URLs your function responds. 如果未提供任何值,则默认值为 <functionname>The default value if none is provided is <functionname>. 有关详细信息,请参阅自定义 HTTP 终结点For more information, see customize the HTTP endpoint.
webHookTypewebHookType WebHookTypeWebHookType 仅支持 1.x 版运行时。Supported only for the version 1.x runtime.

将 HTTP 触发器配置为充当指定提供程序的 webhook 接收器。Configures the HTTP trigger to act as a webhookreceiver for the specified provider. 如果未设置此属性,请不要设置 methods 属性。Don't set the methods property if you set this property. Webhook 类型可以是以下值之一:The webhook type can be one of the following values:
  • genericJson—不包含特定提供程序逻辑的常规用途 webhook 终结点。genericJson—A general-purpose webhook endpoint without logic for a specific provider. 此设置会将请求限制为仅请求使用 HTTP POST 以及内容类型为 application/jsonThis setting restricts requests to only those using HTTP POST and with the application/json content type.
  • github—该函数响应 GitHub Webhookgithub—The function responds to GitHub webhooks. 不要对 GitHub Webhook 使用 authLevel 属性。Do not use the authLevel property with GitHub webhooks. 有关详细信息,请参阅本文后面的“GitHub Webhook”部分。For more information, see the GitHub webhooks section later in this article.
  • slack—该函数响应 Slack Webhookslack—The function responds to Slack webhooks. 不要对 Slack Webhook 使用 authLevel 属性。Do not use the authLevel property with Slack webhooks. 有关详细信息,请参阅本文后面的“Slack Webhook”部分。For more information, see the Slack webhooks section later in this article.


触发器输入类型声明为 HttpRequest 或自定义类型。The trigger input type is declared as either HttpRequest or a custom type. 如果选择 HttpRequest,会获得对请求对象的完全访问权限。If you choose HttpRequest, you get full access to the request object. 对于自定义类型,运行时会尝试分析 JSON 请求正文,以设置对象属性。For a custom type, the runtime tries to parse the JSON request body to set the object properties.

自定义 HTTP 终结点Customize the HTTP endpoint

默认情况下,创建 HTTP 触发器的函数时,可通过以下格式的路由对该函数进行寻址:By default when you create a function for an HTTP trigger, the function is addressable with a route of the form:


在 HTTP 触发器的输入绑定中,可以使用可选 route 属性自定义此路由。You can customize this route using the optional route property on the HTTP trigger's input binding. 例如,以下 function.json 文件定义了 HTTP 触发器的 route 属性:As an example, the following function.json file defines a route property for an HTTP trigger:

    "bindings": [
        "type": "httpTrigger",
        "name": "req",
        "direction": "in",
        "methods": [ "get" ],
        "route": "products/{category:alpha}/{id:int?}"
        "type": "http",
        "name": "res",
        "direction": "out"

通过此配置,现在可以通过以下路由对该函数进行寻址,而不是通过原始路由寻址。Using this configuration, the function is now addressable with the following route instead of the original route.


函数代码可通过此配置支持地址中的两个参数:category 和 id。若要详细了解如何在 URL 中标记路由参数,请参阅在 ASP.NET Core 中进行路由This configuration allows the function code to support two parameters in the address, category and id. For more information on how route parameters are tokenized in a URL, see Routing in ASP.NET Core.

可以将任何 Web API 路由约束与参数配合使用。You can use any Web API Route Constraint with your parameters. 以下 C# 函数代码使用了这两个参数。The following C# function code makes use of both parameters.

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

public static IActionResult Run(HttpRequest req, string category, int? id, ILogger log)
    var message = String.Format($"Category: {category}, ID: {id}");
    return (ActionResult)new OkObjectResult(message);

默认情况下,所有函数路由的前缀均为 api。By default, all function routes are prefixed with api. 还可以使用 host.json 文件中的 extensions.http.routePrefix 属性自定义或删除前缀。You can also customize or remove the prefix using the extensions.http.routePrefix property in your host.json file. 以下示例通过将空字符串用于 host.json 文件中的前缀删除 api 路由前缀。The following example removes the api route prefix by using an empty string for the prefix in the host.json file.

    "extensions": {
        "http": {
            "routePrefix": ""

使用路由参数Using route parameters

定义了函数的 route 模式的路由参数可用于每个绑定。Route parameters that defined a function's route pattern are available to each binding. 例如,如果将某个路由定义为 "route": "products/{id}",则表存储绑定可以在绑定配置中使用 {id} 参数的值。For example, if you have a route defined as "route": "products/{id}" then a table storage binding can use the value of the {id} parameter in the binding configuration.

下面的配置演示如何将 {id} 参数传递到绑定的 rowKeyThe following configuration shows how the {id} parameter is passed to the binding's rowKey.

    "type": "table",
    "direction": "in",
    "name": "product",
    "partitionKey": "products",
    "tableName": "products",
    "rowKey": "{id}"

使用路由参数时,会自动为函数创建 invoke_URL_templateWhen you use route parameters, an invoke_URL_template is automatically created for your function. 你的客户端可以使用 URL 模板来了解在使用 URL 调用函数时需要在 URL 中传递的参数。Your clients can use the URL template to understand the parameters they need to pass in the URL when calling your function using its URL. Azure 门户中导航到某个 HTTP 触发的函数,然后选择“获取函数 URL”。Navigate to one of your HTTP-triggered functions in the Azure portal and select Get function URL.

可以通过用于列出函数获取函数的 Azure 资源管理器 API 以编程方式访问 invoke_URL_templateYou can programmatically access the invoke_URL_template by using the Azure Resource Manager APIs for List Functions or Get Function.

使用客户端标识Working with client identities

如果函数应用使用应用服务身份验证/授权,则可通过代码查看有关已验证身份的客户端的信息。If your function app is using App Service Authentication / Authorization, you can view information about authenticated clients from your code. 此信息以平台注入的请求标头的形式提供。This information is available as request headers injected by the platform.

还可从绑定数据中读取此信息。You can also read this information from binding data. 此功能仅适用于 2.x 及更高版本的 Functions 运行时。This capability is only available to the Functions runtime in 2.x and higher. 而且它目前仅可用于 .NET 语言。It is also currently only available for .NET languages.

有关经过身份验证的客户端的信息以 ClaimsPrincipal 的形式提供。Information regarding authenticated clients is available as a ClaimsPrincipal. ClaimsPrincipal 作为请求上下文的一部分提供,如以下示例中所示:The ClaimsPrincipal is available as part of the request context as shown in the following example:

using System.Net;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

public static IActionResult Run(HttpRequest req, ILogger log)
    ClaimsPrincipal identities = req.HttpContext.User;
    // ...
    return new OkObjectResult();

或者,可直接将 ClaimsPrincipal 作为其他参数包含在函数签名中:Alternatively, the ClaimsPrincipal can simply be included as an additional parameter in the function signature:

using System.Net;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Newtonsoft.Json.Linq;

public static void Run(JObject input, ClaimsPrincipal principal, ILogger log)
    // ...

函数访问密钥Function access keys

Functions 允许使用密钥来增大开发期间访问 HTTP 函数终结点的难度。Functions lets you use keys to make it harder to access your HTTP function endpoints during development. 除非 HTTP 触发的函数中的 HTTP 访问级别设置为 anonymous,否则请求中必须包含 API 访问密钥。Unless the HTTP access level on an HTTP triggered function is set to anonymous, requests must include an API access key in the request.

尽管密钥提供默认的安全机制,但可能需要考虑使用其他选项来保护生产环境中的 HTTP 终结点。While keys provide a default security mechanism, you may want to consider additional options to secure an HTTP endpoint in production. 例如,在公共应用中分发共享机密通常不是一个好做法。For example, it's generally not a good practice to distribute shared secret in public apps. 如果从公共客户端调用函数,则可能需要考虑实施另一种安全机制。If your function is being called from a public client, you may want to consider implementing another security mechanism. 有关详细信息,请参阅在生产环境中保护 HTTP 终结点To learn more, see Secure an HTTP endpoint in production.

续订函数密钥值时,必须手动将更新的密钥值重新分发给调用你的函数的所有客户端。When you renew your function key values, you must manually redistribute the updated key values to all clients that call your function.

授权范围(函数级别)Authorization scopes (function-level)

函数级密钥有两个访问权限作用域:There are two access scopes for function-level keys:

  • 函数 :这些密钥仅适用于在其下定义它们的特定函数。Function : These keys apply only to the specific functions under which they are defined. 这些密钥用作 API 密钥时,只允许访问该函数。When used as an API key, these only allow access to that function.

  • 主机 :主机范围的密钥可用于访问函数应用中的所有函数。Host : Keys with a host scope can be used to access all functions within the function app. 这些密钥用作 API 密钥时,可以访问 Function App 中的任何函数。When used as an API key, these allow access to any function within the function app.

命名每个密钥方便引用,并且在函数和主机级别存在名为“default”的默认密钥。Each key is named for reference, and there is a default key (named "default") at the function and host level. 函数密钥优先于主机密钥。Function keys take precedence over host keys. 如果为两个密钥定义的名称相同,则使用函数密钥。When two keys are defined with the same name, the function key is always used.

主密钥(管理员级别)Master key (admin-level)

每个函数应用还有一个名为 _master 的管理员级主机密钥。Each function app also has an admin-level host key named _master. 除了提供对应用中所有函数的主机级的访问权限外,主密钥还提供对运行时 REST API 的管理访问权限。In addition to providing host-level access to all functions in the app, the master key also provides administrative access to the runtime REST APIs. 无法撤消此密钥。This key cannot be revoked. 设置 admin 访问级别时,请求必须使用主密钥;使用任何其他密钥会导致访问失败。When you set an access level of admin, requests must use the master key; any other key results in access failure.


由于主密钥在函数应用中授予提升的权限,不应与第三方共享此密钥或在本机客户端应用程序中分发此密钥。Due to the elevated permissions in your function app granted by the master key, you should not share this key with third parties or distribute it in native client applications. 选择管理访问级别时请慎重。Use caution when choosing the admin access level.

获取密钥Obtaining keys

密钥作为 Function App 的一部分存储在 Azure 中,并进行了静态加密。Keys are stored as part of your function app in Azure and are encrypted at rest. 若要查看密钥,请创建新的密钥或将密钥滚动更新到新值,在 Azure 门户中导航到某个 HTTP 触发的函数,然后选择“函数密钥”。To view your keys, create new ones, or roll keys to new values, navigate to one of your HTTP-triggered functions in the Azure portal and select Function Keys.

你还可以管理主机密钥。You can also manage host keys. Azure 门户中导航到函数应用,并选择“应用密钥”。Navigate to the function app in the Azure portal and select App keys.

可以使用 Azure 资源管理器 API 以编程方式获取函数和主机密钥。You can obtain function and host keys programmatically by using the Azure Resource Manager APIs. 存在列出函数密钥列出主机密钥的 API,使用部署槽时,等效的 API 是列出函数密钥槽列出主机密钥槽There are APIs to List Function Keys and List Host Keys, and when using deployment slots the equivalent APIs are List Function Keys Slot and List Host Keys Slot.

你还可以使用创建或更新函数机密创建或更新函数机密槽创建或更新主机机密创建或更新主机机密槽 API 以编程方式创建新的函数和主机密钥。You can also create new function and host keys programmatically by using the Create Or Update Function Secret, Create Or Update Function Secret Slot, Create Or Update Host Secret and Create Or Update Host Secret Slot APIs.

可以使用删除函数机密删除函数机密槽删除主机机密删除主机机密槽 API 以编程方式删除函数和主机密钥。Function and host keys can be deleted programmatically by using the Delete Function Secret, Delete Function Secret Slot, Delete Host Secret, and Delete Host Secret Slot APIs.

你也可以使用旧的密钥管理 API 来获取函数密钥,但建议改用 Azure 资源管理器 API。You can also use the legacy key management APIs to obtain function keys, but using the Azure Resource Manager APIs is recommended instead.

API 密钥的授权API key authorization

大多数 HTTP 触发器模板要求在请求中提供 API 密钥。Most HTTP trigger templates require an API key in the request. 因此,HTTP 请求通常类似于以下 URL:So your HTTP request normally looks like the following URL:


可将该密钥包含在名为 code 的查询字符串变量中,如上所示。The key can be included in a query string variable named code, as above. 也可以将它包含在 x-functions-key HTTP 标头中。It can also be included in an x-functions-key HTTP header. 密钥的值可以为任意为函数定义的函数密钥,也可以为任意主机密钥。The value of the key can be any function key defined for the function, or any host key.

可以允许匿名请求,它不需要密钥。You can allow anonymous requests, which do not require keys. 也可要求使用主密钥。You can also require that the master key is used. 可使用绑定 JSON 中的 authLevel 属性更改默认授权级别。You change the default authorization level by using the authLevel property in the binding JSON. 有关详细信息,请参阅触发器 - 配置For more information, see Trigger - configuration.


在本地运行函数时,不管指定的授权级别设置为何,都会禁用授权。When running functions locally, authorization is disabled regardless of the specified authorization level setting. 发布到 Azure 之后,会强制实施触发器中的 authLevel 设置。After publishing to Azure, the authLevel setting in your trigger is enforced.

在生产环境中保护 HTTP 终结点Secure an HTTP endpoint in production

若要全面保护生产环境中的函数终结点,应考虑实现以下函数应用级别的安全选项之一。To fully secure your function endpoints in production, you should consider implementing one of the following function app-level security options. 在使用这些函数应用级别的安全方法之一时,应将 HTTP 触发的函数授权级别设置为 anonymousWhen using one of these function app-level security methods, you should set the HTTP-triggered function authorization level to anonymous.

启用应用服务身份验证/授权Enable App Service Authentication/Authorization

借助应用服务平台可以使用 Azure Active Directory (AAD) 和多个第三方标识提供者对客户端进行身份验证。The App Service platform lets you use Azure Active Directory (AAD) and several third-party identity providers to authenticate clients. 可以使用此策略来实现函数的自定义授权规则,并且可以从函数代码处理用户信息。You can use this strategy to implement custom authorization rules for your functions, and you can work with user information from your function code. 若要了解详细信息,请参阅 Azure 应用服务中的身份验证和授权以及使用客户端标识To learn more, see Authentication and authorization in Azure App Service and Working with client identities.

使用 Azure API 管理 (APIM) 对请求进行身份验证Use Azure API Management (APIM) to authenticate requests

APIM 为传入请求提供了各种 API 安全选项。APIM provides a variety of API security options for incoming requests. 若要了解详细信息,请参阅 API 管理身份验证策略To learn more, see API Management authentication policies. 有了 APIM,可以配置函数应用以接受仅来自 APIM 实例 IP 地址的请求。With APIM in place, you can configure your function app to accept requests only from the IP address of your APIM instance. 若要了解详细信息,请参阅 IP 地址限制To learn more, see IP address restrictions.

在隔离环境中部署函数应用Deploy your function app in isolation

Azure 应用服务环境 (ASE) 提供了用于运行函数的专用宿主环境。Azure App Service Environment (ASE) provides a dedicated hosting environment in which to run your functions. ASE 允许配置单个前端网关,可以使用它对所有传入请求进行身份验证。ASE lets you configure a single front-end gateway that you can use to authenticate all incoming requests. 有关详细信息,请参阅为应用服务环境配置 Web 应用程序防火墙 (WAF)For more information, see Configuring a Web Application Firewall (WAF) for App Service Environment.



Webhook 模式仅适用于 1.x 版 Functions 运行时。Webhook mode is only available for version 1.x of the Functions runtime. 进行此更改是为了提高 2.x 及更高版本中 HTTP 触发器的性能。This change was made to improve the performance of HTTP triggers in version 2.x and higher.

在 1.x 版中,Webhook 模板为 Webhook 有效负载提供了额外的验证。In version 1.x, webhook templates provide additional validation for webhook payloads. 在 2.x 及更高版本中,基本 HTTP 触发器仍正常工作,且是针对 Webhook 的推荐方法。In version 2.x and higher, the base HTTP trigger still works and is the recommended approach for webhooks.

GitHub WebhookGitHub webhooks

要响应 GitHub webhook,首先请创建包含 HTTP 触发器的函数,并将 webHookType 属性设置为 githubTo respond to GitHub webhooks, first create your function with an HTTP Trigger, and set the webHookType property to github. 然后将其 URL 和 API 密钥复制到 GitHub 存储库的“添加 Webhook”页。Then copy its URL and API key into the Add webhook page of your GitHub repository.

显示如何添加函数的 Webhook 的屏幕截图。

Slack WebhookSlack webhooks

Slack webhook 为用户生成令牌,而非让用户指定它,所以必须使用 Slack 中的令牌配置特定于函数的密钥。The Slack webhook generates a token for you instead of letting you specify it, so you must configure a function-specific key with the token from Slack. 请参阅授权密钥See Authorization keys.

Webhook 和密钥Webhooks and keys

Webhook 授权由属于 HTTP 触发器的 webhook 接收器组件处理,其机制因 webhook 类型而异。Webhook authorization is handled by the webhook receiver component, part of the HTTP trigger, and the mechanism varies based on the webhook type. 每种机制都依赖于一个密钥。Each mechanism does rely on a key. 默认情况下,使用名为“default”的函数密钥。By default, the function key named "default" is used. 要使用其他密钥,请将 webhook 提供程序配置为使用以下方式之一的请求发送密钥名称:To use a different key, configure the webhook provider to send the key name with the request in one of the following ways:

  • 查询字符串:提供程序通过 clientid 查询字符串参数(例如,https://<APP_NAME><FUNCTION_NAME>?clientid=<KEY_NAME>)传递密钥名称。Query string: The provider passes the key name in the clientid query string parameter, such as https://<APP_NAME><FUNCTION_NAME>?clientid=<KEY_NAME>.
  • 请求标头:提供程序通过 x-functions-clientid 标头传递密钥名称。Request header: The provider passes the key name in the x-functions-clientid header.

内容类型Content types

将二进制文件和窗体数据传递给非 C# 函数需要使用适当的 content-type 标头。Passing binary and form data to a non-C# function requires that you use the appropriate content-type header. 支持的内容类型包括 octet-stream(适用于二进制数据)和多部分类型Supported content types include octet-stream for binary data and multipart types.

已知问题Known issues

在非 C# 函数中,使用 content-type image/jpeg 发送的请求会导致向函数传递 string 值。In non-C# functions, requests sent with the content-type image/jpeg results in a string value passed to the function. 在这种情况下,可以手动将 string 值转换为字节数组以访问原始二进制数据。In cases like these, you can manually convert the string value to a byte array to access the raw binary data.


HTTP 请求长度限制为 100 MB(104,857,600 字节),并且 URL 长度限制为 4 KB(4,096 字节)。The HTTP request length is limited to 100 MB (104,857,600 bytes), and the URL length is limited to 4 KB (4,096 bytes). 这些限制由运行时的 Web.config 文件httpRuntime 元素指定。These limits are specified by the httpRuntime element of the runtime's Web.config file.

如果使用 HTTP 触发器的函数未在 230 秒内完成,Azure 负载均衡器将超时并返回 HTTP 502 错误。If a function that uses the HTTP trigger doesn't complete within 230 seconds, the Azure Load Balancer will time out and return an HTTP 502 error. 该函数将继续运行,但将无法返回 HTTP 响应。The function will continue running but will be unable to return an HTTP response. 对于长时间运行的函数,我们建议你遵循异步模式,并返回可以 ping 通请求状态的位置。For long-running functions, we recommend that you follow async patterns and return a location where you can ping the status of the request. 有关函数可以运行多长时间的信息,请参阅缩放和托管 - 消耗计划For information about how long a function can run, see Scale and hosting - Consumption plan.

后续步骤Next steps