Azure Functions HTTP 觸發程序和繫結Azure Functions HTTP triggers and bindings

此文章說明如何在 Azure Functions 中使用 HTTP 觸發程序和輸出繫結。This article explains how to work with HTTP triggers and output bindings in Azure Functions.

您可以自訂 HTTP 觸發程序來回應 WebhookAn HTTP trigger can be customized to respond to webhooks.

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

提示

如果您打算使用 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.

本文中的程式碼預設為使用 .NET Core 的語法,用於2.x 版和更高版本的函式。The code in this article defaults to the syntax which uses .NET Core, used in Functions version 2.x and higher. 如需 1.x 語法的資訊,請參閱 1.x 函式範本For information on the 1.x syntax, see the 1.x functions templates.

套件 - Functions 1.xPackages - Functions 1.x

Microsoft.Azure.WebJobs.Extensions.Http NuGet 套件 (1.x 版) 中提供 HTTP 繫結。The HTTP bindings are provided in the Microsoft.Azure.WebJobs.Extensions.Http NuGet package, version 1.x. 套件的原始程式碼位於 azure-webjobs-sdk-extensions GitHub 存放庫中。Source code for the package is in the azure-webjobs-sdk-extensions GitHub repository.

所有的開發環境中都會自動賦予此繫結的支援。Support for this binding is automatically provided in all development environments. 您不需要手動安裝套件或註冊擴充功能。You don't have to manually install the package or register the extension.

封裝-函數2.x 和更新版本Packages - Functions 2.x and higher

Microsoft.Azure.WebJobs.Extensions.Http NuGet 套件 (3.x 版) 中提供 HTTP 繫結。The HTTP bindings are provided in the Microsoft.Azure.WebJobs.Extensions.Http NuGet package, version 3.x. 套件的原始程式碼位於 azure-webjobs-sdk-extensions GitHub 存放庫中。Source code for the package is in the azure-webjobs-sdk-extensions GitHub repository.

所有的開發環境中都會自動賦予此繫結的支援。Support for this binding is automatically provided in all development environments. 您不需要手動安裝套件或註冊擴充功能。You don't have to manually install the package or register the extension.

觸發程序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 觸發程式會以函式1.x 中的空白主體傳回 HTTP 200 OK,204或在函式2.x 和更新版本中沒有具有空白主體的內容。By default, an HTTP trigger returns HTTP 200 OK with an empty body in Functions 1.x, or HTTP 204 No Content with an empty body in Functions 2.x and higher. 若要修改回應,請設定 HTTP 輸出繫結To modify the response, configure an HTTP output binding.

觸發程序 - 範例Trigger - example

下列範例會顯示在查詢字串或 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.

[FunctionName("HttpTriggerCSharp")]
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 = await new StreamReader(req.Body).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");
}

觸發程序 - 屬性Trigger - attributes

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 Trigger - configuration.

這個範例示範如何使用HttpTrigger屬性。This example demonstrates how to use the HttpTrigger attribute.

[FunctionName("HttpTriggerCSharp")]
public static Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req)
{
    ...
}

如需完整範例,請參閱觸發程式範例For a complete example, see the trigger example.

觸發程式 - 設定Trigger - configuration

下表說明您在 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 property 說明Description
typetype n/an/a 必要項目 - 必須設定為 httpTriggerRequired - must be set to httpTrigger.
directiondirection n/an/a 必要項目 - 必須設定為 inRequired - must be set to in.
namename n/an/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 路由Route 會定義路由範本,從而控制函式所要回應的要求 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 webhook receiver 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/json 內容類型的要求。This 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. 請勿使用 authLevel 屬性搭配 GitHub Webhook。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. 請勿使用 authLevel 屬性搭配 Slack Webhook。Do not use the authLevel property with Slack webhooks. 如需詳細資訊,請參閱本文稍後的 Slack Webhook 一節。For more information, see the Slack webhooks section later in this article.

觸發程序 - 使用方式Trigger - usage

觸發程式輸入類型會宣告為 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://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>

您可以在 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.

http://<APP_NAME>.azurewebsites.net/api/products/electronics/357

這可讓該函式程式碼在位址中支援兩個參數,即 categoryidThis allows the function code to support two parameters in the address, category and id.

您可以將任何 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);
}

所有函式路由預設前面都會加上 apiBy default, all function routes are prefixed with api. 您也可以在 host.json 檔案中使用 http.routePrefix 屬性來自訂或移除前置詞。You can also customize or remove the prefix using the 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.

{
    "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}"
}

使用用戶端身分識別Working with client identities

如果您的函式應用程式使用 App Service 驗證/授權,您可以透過程式碼來檢視已驗證的用戶端相關資訊。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 和更新版本中的函式執行時間。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)
{
    // ...
    return;
}

授權金鑰Authorization keys

Functions 可讓您使用金鑰來提高開發期間存取 HTTP 函式端點的困難度。Functions lets you use keys to make it harder to access your HTTP function endpoints during development. 標準 HTTP 觸發程序可要求在要求中有這樣的 API 金鑰存在。A standard HTTP trigger may require such an API key be present in the request.

重要

雖然金鑰可能有助於在開發期間遮蔽您的 HTTP 端點,但這並不適合用來作為在生產環境中保護 HTTP 觸發程序的方式。While keys may help obfuscate your HTTP endpoints during development, they are not intended as a way to secure an HTTP trigger in production. 若要深入了解,請參閱在生產環境中保護 HTTP 端點To learn more, see Secure an HTTP endpoint in production.

注意

在 Functions 1.x 執行階段中,Webhook 提供者可以使用金鑰以多種方式授權要求,端視提供者支援的方式而定。In the Functions 1.x runtime, webhook providers may use keys to authorize requests in a variety of ways, depending on what the provider supports. Webhook 和金鑰中提供了這方面的相關說明。This is covered in Webhooks and keys. 2.x 版和更新版本中的函數執行時間不包含 webhook 提供者的內建支援。The Functions runtime in version 2.x and higher does not include built-in support for webhook providers.

金鑰類型有兩種:There are two types of keys:

  • 主機金鑰:這些金鑰由函數應用程式中所有的函式共用。Host keys: These keys are shared by all functions within the function app. 當做為 API 金鑰使用時,這些金鑰會允許存取函數應用程式中的任何函式。When used as an API key, these allow access to any function within the function app.
  • 函式金鑰:這些金鑰僅適用於據以定義它們的特定函式。Function keys: 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.

每個金鑰均為具名以供參考,並且在函式和主機層級有一預設金鑰 (名稱為 "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.

每個函數應用程式都有特殊的主要金鑰Each function app also has a special master key. 此金鑰是一個名為 _master 的主機金鑰,它會提供對執行階段 API 的系統管理存取權。This key is a host key named _master, which provides administrative access to the runtime APIs. 無法撤銷此金鑰。This key cannot be revoked. 當您將授權等級設定為 admin 時,要求就必須使用主要金鑰;任何其他金鑰則會導致授權失敗。When you set an authorization level of admin, requests must use the master key; any other key results in authorization 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 authorization level.

取得金鑰Obtaining keys

金鑰會當作您函數應用程式的一部分儲存於 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 Manage.

在入口網站中管理函式金鑰。

您可以使用金鑰管理 api以程式設計方式取得功能鍵。You may obtain function keys programmatically by using Key management APIs.

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:

https://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>?code=<API_KEY>

金鑰可包含在名為 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 be 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. 在容器中的本機執行時,仍然需要金鑰。Keys are still required when running locally in a container.

在生產環境中保護 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:

  • 為您的函數應用程式開啟「App Service 驗證/授權」。Turn on App Service Authentication / Authorization for your function app. App Service 平臺可讓您使用 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 to implement custom authorization rules for your functions, and you can work with user information from your function code. 若要深入了解,請參閱 Azure App Service 中的驗證與授權使用用戶端身分識別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.

  • 將您的函數應用程式部署至 Azure App Service Environment (ASE)。Deploy your function app to an Azure App Service Environment (ASE). ASE 提供一個可供執行您函式的專用主控環境。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. 如需詳細資訊,請參閱設定 App Service Environment 的 Web 應用程式防火牆 (WAF)For more information, see Configuring a Web Application Firewall (WAF) for App Service Environment.

使用其中一個函數應用層級的安全性方法時,您應該將 HTTP 觸發的函式授權層級設定為 anonymousWhen using one of these function app-level security methods, you should set the HTTP-triggered function authorization level to anonymous.

WebhookWebhooks

注意

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.

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 授權是由 Webhook 接收器元件 (HTTP 觸發程序的一部分) 處理,處理機制則會以 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>.azurewebsites.net/api/<FUNCTION_NAME>?clientid=<KEY_NAME>Query string: The provider passes the key name in the clientid query string parameter, such as https://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>?clientid=<KEY_NAME>.
  • 要求標頭︰提供者在 x-functions-clientid 標頭中傳遞金鑰名稱。Request header: The provider passes the key name in the x-functions-clientid header.

觸發程序的 - 限制Trigger - limits

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 Load Balancer將會超時,並傳回 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. 對於長時間執行的函式,建議您遵循非同步模式,並傳回可以偵測要求狀態的位置。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.

輸出Output

使用 HTTP 輸出繫結來回應 HTTP 要求傳送者。Use the HTTP output binding to respond to the HTTP request sender. 此繫結需要 HTTP 觸發程序,並可讓您自訂與觸發程序要求相關聯的回應。This binding requires an HTTP trigger and allows you to customize the response associated with the trigger's request. 如果未提供 HTTP 輸出系結,HTTP 觸發程式會以函式1.x 中的空白主體傳回 HTTP 200 OK,或在函式2.x 和更新版本中沒有具有空白主體的 HTTP 204。If an HTTP output binding is not provided, an HTTP trigger returns HTTP 200 OK with an empty body in Functions 1.x, or HTTP 204 No Content with an empty body in Functions 2.x and higher.

輸出 - 設定Output - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性。The following table explains the binding configuration properties that you set in the function.json file. 就 C# 類別程式庫而言,沒有任何屬性 (Attribute) 的屬性 (Property) 與這些 function.json 屬性 (Property) 對應。For C# class libraries, there are no attribute properties that correspond to these function.json properties.

屬性Property 說明Description
typetype 必須設為 httpMust be set to http.
directiondirection 必須設為 outMust be set to out.
namename 函式程式碼中用於回應的變數名稱,或要使用傳回值的 $returnThe variable name used in function code for the response, or $return to use the return value.

輸出 - 使用方式Output - usage

若要傳送 HTTP 回應,請使用語言標準回應模式。To send an HTTP response, use the language-standard response patterns. 在 C# 或 C# 指令碼 中,讓函式傳回類型成為 IActionResultTask<IActionResult>In C# or C# script, make the function return type IActionResult or Task<IActionResult>. 在 C# 中,傳回值屬性並非必要。In C#, a return value attribute isn't required.

如需範例回應,請參閱觸發程序範例For example responses, see the trigger example.

host.json 設定host.json settings

本節說明2.x 版和更高版本中可供此系結使用的全域設定。This section describes the global configuration settings available for this binding in versions 2.x and higher. 下面的範例 host. json 檔案僅包含此系結的2.x 版和設定。The example host.json file below contains only the version 2.x+ settings for this binding. 如需有關2.x 版和更早版本中的全域設定的詳細資訊,請參閱Azure Functions 的 host. json 參考For more information about global configuration settings in versions 2.x and beyond, see host.json reference for Azure Functions.

注意

有關 Functions 1.x 中 host.json 的參考,請參閱適用於 Azure Functions 1.x 的 host.json 參考For a reference of host.json in Functions 1.x, see host.json reference for Azure Functions 1.x.

{
    "extensions": {
        "http": {
            "routePrefix": "api",
            "maxOutstandingRequests": 200,
            "maxConcurrentRequests": 100,
            "dynamicThrottlesEnabled": true,
            "hsts": {
                "isEnabled": true,
                "maxAge": "10"
            },
            "customHeaders": {
                "X-Content-Type-Options": "nosniff"
            }
        }
    }
}
屬性Property 預設Default 說明Description
customHeaderscustomHeaders none 可讓您設定 HTTP 回應中的自訂標頭。Allows you to set custom headers in the HTTP response. 先前的範例會將 X-Content-Type-Options 標頭新增至回應,以避免內容類型探查。The previous example adds the X-Content-Type-Options header to the response to avoid content type sniffing.
dynamicThrottlesEnableddynamicThrottlesEnabled true*true* 啟用時,此設定會促使要求處理管線定期檢查系統效能計數器,例如連線/執行緒/處理程序/記憶體/CPU/其他,而且如果這些計數器中任一個超過內建的臨界值上限 (80%),則要求會遭到拒絕,並包含 429「忙碌」的回應,直到計數器回到正常水平。When enabled, this setting causes the request processing pipeline to periodically check system performance counters like connections/threads/processes/memory/cpu/etc. and if any of those counters are over a built-in high threshold (80%), requests will be rejected with a 429 "Too Busy" response until the counter(s) return to normal levels.
*耗用量方案中的預設值為 true*The default in a Consumption plan is true. 專用方案中的預設值為 falseThe default in a Dedicated plan is false.
hstshsts 未啟用not enabled isEnabled 設定為 true時,會強制執行.Net Core 的 HTTP 嚴格傳輸安全性(HSTS)行為,如HstsOptions 類別中所定義。When isEnabled is set to true, the HTTP Strict Transport Security (HSTS) behavior of .NET Core is enforced, as defined in the HstsOptions class. 上述範例也會將maxAge屬性設定為10天。The above example also sets the maxAge property to 10 days. 支援的 hsts 屬性包括:Supported properties of hsts are:
屬性Property說明Description
excludedHostsexcludedHosts未新增 HSTS 標頭之主機名稱的字串陣列。A string array of host names for which the HSTS header isn't added.
includeSubDomainsincludeSubDomains布林值,指出是否啟用嚴格傳輸安全性標頭的 includeSubDomain 參數。Boolean value that indicates whether the includeSubDomain parameter of the Strict-Transport-Security header is enabled.
maxAgemaxAge定義嚴格傳輸安全性標頭的最大壽命參數的字串。String that defines the max-age parameter of the Strict-Transport-Security header.
預先載入preload布林值,指出是否啟用嚴格傳輸安全性標頭的預先載入參數。Boolean that indicates whether the preload parameter of the Strict-Transport-Security header is enabled.
maxConcurrentRequestsmaxConcurrentRequests 100*100* 平行執行的 HTTP 函式數目上限。The maximum number of HTTP functions that are executed in parallel. 這可讓您控制並行作業,幫助您管理資源使用率。This allows you to control concurrency, which can help manage resource utilization. 例如,您可能有一個使用大量系統資源(記憶體/cpu/通訊端)的 HTTP 函式,因此當並行處理太高時,會造成問題。For example, you might have an HTTP function that uses a lot of system resources (memory/cpu/sockets) such that it causes issues when concurrency is too high. 或者,如果函式對第三方服務發出傳出要求,則需要限制這些呼叫的速率。Or you might have a function that makes outbound requests to a third party service, and those calls need to be rate limited. 在這些情況下,套用節流會有所幫助。In these cases, applying a throttle here can help.
*耗用量方案的預設值為100。*The default for a Consumption plan is 100. 專用方案的預設值是無限制的(-1)。The default for a Dedicated plan is unbounded (-1).
maxOutstandingRequestsmaxOutstandingRequests 200*200* 在任何指定時間保留的未完成要求數目上限。The maximum number of outstanding requests that are held at any given time. 此限制包括已排入佇列但尚未開始執行的要求,以及任何進行中的執行。This limit includes requests that are queued but have not started executing, as well as any in progress executions. 會以 429「忙碌」回應來拒絕任何超過此限制的連入要求。Any incoming requests over this limit are rejected with a 429 "Too Busy" response. 這樣可讓呼叫者採用以時間為基礎的重試策略,並且也協助您控制要求延遲的上限。That allows callers to employ time-based retry strategies, and also helps you to control maximum request latencies. 此動作只會控制在指令碼主機執行路徑內發生的佇列處理。This only controls queuing that occurs within the script host execution path. 其他佇列 (例如 ASP.NET 要求佇列) 仍然有效,且不受此設定的影響。Other queues such as the ASP.NET request queue will still be in effect and unaffected by this setting.
*耗用量方案的預設值為200。*The default for a Consumption plan is 200. 專用方案的預設值是無限制的(-1)。The default for a Dedicated plan is unbounded (-1).
routePrefixroutePrefix apiapi 適用於所有路由的路由前置詞。The route prefix that applies to all routes. 若要移除預設前置詞,請使用空字串。Use an empty string to remove the default prefix.

後續步驟Next steps

深入了解 Azure Functions 觸發程序和繫結Learn more about Azure functions triggers and bindings