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 的 Functions 2.x 語法。The code in this article defaults to Functions 2.x syntax which uses .NET Core. 如需 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.

套件 - Functions 2.xPackages - Functions 2.x

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 觸發程序會在 Functions 1.x 中傳回「HTTP 200 正常」與空白主體,或在 Functions 1 2.x 中傳回「HTTP 204 沒有內容」與空白主體。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. 若要修改回應,請設定 HTTP 輸出繫結To modify the response, configure an HTTP output binding.

觸發程序 - 範例Trigger - example

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

觸發程序 - C# 範例Trigger - C# 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");
}

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

下列範例示範 function.json 檔案中的觸發程序繫結,以及使用此繫結的 C# 指令碼函式The following example shows a trigger binding in a function.json file and a C# script function that uses the binding. 函式會尋找 name 參數,其位於查詢字串或 HTTP 要求的主體。The function looks for a name parameter either in the query string or the body of the HTTP request.

以下是 function.json 檔案:Here's the function.json file:

{
    "disabled": false,
    "bindings": [
        {
            "authLevel": "function",
            "name": "req",
            "type": "httpTrigger",
            "direction": "in",
            "methods": [
                "get",
                "post"
            ]
        },
        {
            "name": "$return",
            "type": "http",
            "direction": "out"
        }
    ]
}

設定章節會說明這些屬性。The configuration section explains these properties.

以下是繫結至 HttpRequest 的 C# 指令碼:Here's C# script code that binds to HttpRequest:

#r "Newtonsoft.Json"

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

public static async Task<IActionResult> Run(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");
}

您可以繫結至自訂的物件,而不是 HttpRequestYou can bind to a custom object instead of HttpRequest. 會從要求主體建立這個物件,並剖析成 JSON。This object is created from the body of the request and parsed as JSON. 同樣地,類型可以傳遞至 HTTP 回應輸出繫結,並加以傳回作為狀態碼 200 的回應主體。Similarly, a type can be passed to the HTTP response output binding and returned as the response body, along with a 200 status code.

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

public static string Run(Person person, ILogger log)
{   
    return person.Name != null
        ? (ActionResult)new OkObjectResult($"Hello, {person.Name}")
        : new BadRequestObjectResult("Please pass an instance of Person.");
}

public class Person {
     public string Name {get; set;}
}

觸發程序 - F# 範例Trigger - F# example

下列範例示範 function.json 檔案中的觸發程序繫結,以及使用此繫結的 F# 函式The following example shows a trigger binding in a function.json file and an F# function that uses the binding. 函式會尋找 name 參數,其位於查詢字串或 HTTP 要求的主體。The function looks for a name parameter either in the query string or the body of the HTTP request.

以下是 function.json 檔案:Here's the function.json file:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

設定章節會說明這些屬性。The configuration section explains these properties.

以下是 F# 程式碼:Here's the F# code:

open System.Net
open System.Net.Http
open FSharp.Interop.Dynamic

let Run(req: HttpRequestMessage) =
    async {
        let q =
            req.GetQueryNameValuePairs()
                |> Seq.tryFind (fun kv -> kv.Key = "name")
        match q with
        | Some kv ->
            return req.CreateResponse(HttpStatusCode.OK, "Hello " + kv.Value)
        | None ->
            let! data = Async.AwaitTask(req.Content.ReadAsAsync<obj>())
            try
                return req.CreateResponse(HttpStatusCode.OK, "Hello " + data?name)
            with e ->
                return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
    } |> Async.StartAsTask

您需要 project.json 檔案,以使用 NuGet 來參考 FSharp.Interop.DynamicDynamitey 組件,如下列範例所示:You need a project.json file that uses NuGet to reference the FSharp.Interop.Dynamic and Dynamitey assemblies, as shown in the following example:

{
  "frameworks": {
    "net46": {
      "dependencies": {
        "Dynamitey": "1.0.2",
        "FSharp.Interop.Dynamic": "3.0.0"
      }
    }
  }
}

觸發程序 - JavaScript 範例Trigger - JavaScript example

下列範例示範的是使用繫結之 function.json 檔案,以及 JavaScript 函式中的觸發程序繫結。The following example shows a trigger binding in a function.json file and a JavaScript function that uses the binding. 函式會尋找 name 參數,其位於查詢字串或 HTTP 要求的主體。The function looks for a name parameter either in the query string or the body of the HTTP request.

以下是 function.json 檔案:Here's the function.json file:

{
    "disabled": false,    
    "bindings": [
        {
            "authLevel": "function",
            "type": "httpTrigger",
            "direction": "in",
            "name": "req"
        },
        {
            "type": "http",
            "direction": "out",
            "name": "res"
        }
    ]
}

設定章節會說明這些屬性。The configuration section explains these properties.

以下是 JavaScript 程式碼:Here's the JavaScript code:

module.exports = function(context, req) {
    context.log('Node.js HTTP trigger function processed a request. RequestUri=%s', req.originalUrl);

    if (req.query.name || (req.body && req.body.name)) {
        context.res = {
            // status defaults to 200 */
            body: "Hello " + (req.query.name || req.body.name)
        };
    }
    else {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
    context.done();
};

觸發程序 - Python 範例Trigger - Python example

下列範例示範 function.json 檔案中的觸發程序繫結,以及使用此繫結的 Python 函式The following example shows a trigger binding in a function.json file and a Python function that uses the binding. 函式會尋找 name 參數,其位於查詢字串或 HTTP 要求的主體。The function looks for a name parameter either in the query string or the body of the HTTP request.

以下是 function.json 檔案:Here's the function.json file:

{
    "scriptFile": "__init__.py",
    "disabled": false,    
    "bindings": [
        {
            "authLevel": "function",
            "type": "httpTrigger",
            "direction": "in",
            "name": "req"
        },
        {
            "type": "http",
            "direction": "out",
            "name": "res"
        }
    ]
}

設定章節會說明這些屬性。The configuration section explains these properties.

以下是 Python 程式碼:Here's the Python code:

import logging
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello {name}!")
    else:
        return func.HttpResponse(
            "Please pass a name on the query string or in the request body",
            status_code=400
        )

觸發程序 - Java 範例Trigger - Java examples

下列範例示範 function.json 檔案中的 HTTP 觸發程序繫結,以及使用該繫結的個別 Java 函式The following examples show the HTTP trigger binding in a function.json file and the respective Java functions that use the binding.

以下是 function.json 檔案:Here's the function.json file:

{
    "disabled": false,    
    "bindings": [
        {
            "authLevel": "anonymous",
            "type": "httpTrigger",
            "direction": "in",
            "name": "req"
        },
        {
            "type": "http",
            "direction": "out",
            "name": "res"
        }
    ]
}

讀取查詢字串的參數 (Java)Read parameter from the query string (Java)

此範例會從查詢字串中讀取名為 id 的參數,並使用它來建立傳回至用戶端且內容類型為 application/json 的 JSON 文件。This example reads a parameter, named id, from the query string, and uses it to build a JSON document returned to the client, with content type application/json.

    @FunctionName("TriggerStringGet")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", 
              methods = {HttpMethod.GET}, 
              authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {
        
        // Item list
        context.getLogger().info("GET parameters are: " + request.getQueryParameters());

        // Get named parameter
        String id = request.getQueryParameters().getOrDefault("id", "");

        // Convert and display
        if (id.isEmpty()) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        } 
        else {
            // return JSON from to the client
            // Generate document
            final String name = "fake_name";
            final String jsonDocument = "{\"id\":\"" + id + "\", " + 
                                         "\"description\": \"" + name + "\"}";
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(jsonDocument)
                          .build();
        }
    }

從 POST 要求讀取主體 (Java)Read body from a POST request (Java)

此範例會讀取 POST 要求的主體,作為 String,並使用它來建立傳回至用戶端且內容類型為 application/json 的 JSON 文件。This example reads the body of a POST request, as a String, and uses it to build a JSON document returned to the client, with content type application/json.

    @FunctionName("TriggerStringPost")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", 
              methods = {HttpMethod.POST}, 
              authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {
        
        // Item list
        context.getLogger().info("Request body is: " + request.getBody().orElse(""));

        // Check request body
        if (!request.getBody().isPresent()) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        } 
        else {
            // return JSON from to the client
            // Generate document
            final String body = request.getBody().get();
            final String jsonDocument = "{\"id\":\"123456\", " + 
                                         "\"description\": \"" + body + "\"}";
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(jsonDocument)
                          .build();
        }
    }

從路由讀取參數 (Java)Read parameter from a route (Java)

此範例會從路由路徑讀取名為 id 的必要參數,和選用參數 name,然後使用這些參數來建立傳回至用戶端且內容類型為 application/json 的 JSON 文件。This example reads a mandatory parameter, named id, and an optional parameter name from the route path, and uses them to build a JSON document returned to the client, with content type application/json. TT

    @FunctionName("TriggerStringRoute")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", 
              methods = {HttpMethod.GET}, 
              authLevel = AuthorizationLevel.ANONYMOUS,
              route = "trigger/{id}/{name=EMPTY}") // name is optional and defaults to EMPTY
            HttpRequestMessage<Optional<String>> request,
            @BindingName("id") String id,
            @BindingName("name") String name,
            final ExecutionContext context) {
        
        // Item list
        context.getLogger().info("Route parameters are: " + id);

        // Convert and display
        if (id == null) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        } 
        else {
            // return JSON from to the client
            // Generate document
            final String jsonDocument = "{\"id\":\"" + id + "\", " + 
                                         "\"description\": \"" + name + "\"}";
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(jsonDocument)
                          .build();
        }
    }

從 POST 要求讀取 POJO 內文 (Java)Read POJO body from a POST request (Java)

以下是此範例中所參照 ToDoItem 類別的程式碼:Here is the code for the ToDoItem class, referenced in this example:


public class ToDoItem {

  private String id;
  private String description;  

  public ToDoItem(String id, String description) {
    this.id = id;
    this.description = description;
  }

  public String getId() {
    return id;
  }

  public String getDescription() {
    return description;
  }
  
  @Override
  public String toString() {
    return "ToDoItem={id=" + id + ",description=" + description + "}";
  }
}

此範例會讀取 POST 要求的主體。This example reads the body of a POST request. 要求主體會自動還原序列化至 ToDoItem 物件,並傳回至用戶端,且內容類型為 application/jsonThe request body gets automatically de-serialized into a ToDoItem object, and is returned to the client, with content type application/json. ToDoItem 參數會在指派給 HttpMessageResponse.Builder 類別的 body 屬性時,由 Functions 執行階段序列化。The ToDoItem parameter is serialized by the Functions runtime as it is assigned to the body property of the HttpMessageResponse.Builder class.

    @FunctionName("TriggerPojoPost")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", 
              methods = {HttpMethod.POST}, 
              authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<ToDoItem>> request,
            final ExecutionContext context) {
        
        // Item list
        context.getLogger().info("Request body is: " + request.getBody().orElse(null));

        // Check request body
        if (!request.getBody().isPresent()) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        } 
        else {
            // return JSON from to the client
            // Generate document
            final ToDoItem body = request.getBody().get();
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(body)
                          .build();
        }
    }

觸發程序 - 屬性Trigger - attributes

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

您可以設定授權層級和屬性建構參數中可允許的 HTTP 方法,並有 webhook 類型和路由範本的內容。You can set the authorization level and allowable HTTP methods in attribute constructor parameters, and there are properties for webhook type and route template. 如需這些設定的詳細資訊,請參閱觸發程序 - 組態For more information about these settings, see Trigger - configuration. 以下是方法簽章中的 HttpTrigger 屬性:Here's an HttpTrigger attribute in a method signature:

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

如需完整範例,請參閱觸發程序 - C# 範例For a complete example, see Trigger - C# 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

針對 C# 和 F# 函式,您可以宣告觸發程序輸入的類型為 HttpRequest 或自訂類型。For C# and F# functions, you can declare the type of your trigger input to be 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.

對於 JavaScript 函式,Functions 執行階段提供要求主體而非要求物件。For JavaScript functions, the Functions runtime provides the request body instead of the request object. 如需詳細資訊,請參閱 JavaScript 觸發程序範例For more information, see the JavaScript trigger example.

自訂 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://<yourapp>.azurewebsites.net/api/<funcname>

您可以在 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://<yourapp>.azurewebsites.net/api/products/electronics/357

這可讓該函式程式碼在位址中支援兩個參數,即 categoryid。您可以將任何 Web API 路由條件約束與您的參數搭配使用。This allows the function code to support two parameters in the address, category and id. You can use any Web API Route Constraint with your parameters. 下列 C# 函式程式碼會同時利用這兩個參數。The following C# function code makes use of both parameters.

public static Task<IActionResult> Run(HttpRequest req, string category, int? id, ILogger log)
{
    if (id == null)
    {
        return (ActionResult)new OkObjectResult($"All {category} items were requested.");
    }
    else
    {
        return (ActionResult)new OkObjectResult($"{category} item with id = {id} has been requested.");
    }
    
    // -----
    log.LogInformation($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
}

以下是使用相同路由參數的 Node.js 函式程式碼。Here is Node.js function code that uses the same route parameters.

module.exports = function (context, req) {

    var category = context.bindingData.category;
    var id = context.bindingData.id;

    if (!id) {
        context.res = {
            // status defaults to 200 */
            body: "All " + category + " items were requested."
        };
    }
    else {
        context.res = {
            // status defaults to 200 */
            body: category + " item with id = " + id + " was requested."
        };
    }

    context.done();
}

所有函式路由預設前面都會加上 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": ""
    }
}

使用用戶端身分識別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. 這項功能僅適用於 Functions 2.x 執行階段。This capability is only available to the Functions 2.x runtime. 它目前也僅適用於 .NET 語言。It is also currently only available for .NET languages.

在 .NET 語言中,此資訊會以 ClaimsPrincipal 形式提供。In .NET languages, this information 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:

#r "Newtonsoft.Json"

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 version 2.x runtime 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 可透過程式設計方式取得函式金鑰。There is no supported API for programmatically obtaining function keys.

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 authentication 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:

  • 為您的函數應用程式開啟「App Service 驗證/授權」。Turn on App Service Authentication / Authorization for your function app. App Service 平台可讓您使用 Azure Active Directory (AAD) 和數個協力廠商身分識別提供者來驗證用戶端。The App Service platform lets 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 authentication 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.

在版本 1.x 中,Webhook 範本會提供 Webhook 承載的額外驗證。In version 1.x, webhook templates provide additional validation for webhook payloads. 在 2.x 版中,基底 HTTP 觸發程序仍然可運作,並且對 Webhook 來說是建議採用的方法。In version 2.x, 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 觸發程序的函式未在約 2.5 分鐘內完成,閘道將會逾時並傳回 HTTP 502 錯誤。If a function that uses the HTTP trigger doesn't complete within about 2.5 minutes, the gateway 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.

觸發程序 - host.json 屬性Trigger - host.json properties

host.json 檔案包含控制 HTTP 觸發程序行為的設定。The host.json file contains settings that control HTTP trigger behavior.

{
    "http": {
        "routePrefix": "api",
        "maxOutstandingRequests": 200,
        "maxConcurrentRequests": 100,
        "dynamicThrottlesEnabled": true
    }
}
屬性Property 預設值Default 描述Description
routePrefixroutePrefix apiapi 適用於所有路由的路由前置詞。The route prefix that applies to all routes. 若要移除預設前置詞,請使用空字串。Use an empty string to remove the default prefix.
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. *預設版本 1.x 未繫結 (-1)。*The default for version 1.x is unbounded (-1). 在取用方案中,版本 2.x 的預設值是 200。The default for version 2.x in a consumption plan is 200. 預設版本 2.x 專用的方案中未繫結 (-1)。The default for version 2.x in a dedicated plan is unbounded (-1).
maxConcurrentRequestsmaxConcurrentRequests 100*100* 要平行執行的 HTTP 函式數目上限。The maximum number of http functions that will be 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. *預設版本 1.x 未繫結 (-1)。*The default for version 1.x is unbounded (-1). 在取用方案中,版本 2.x 的預設值是 100。The default for version 2.x in a consumption plan is 100. 預設版本 2.x 專用的方案中未繫結 (-1)。The default for version 2.x in a dedicated plan is unbounded (-1).
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. *預設版本 1.x 為 false。*The default for version 1.x is false. 在取用方案中,版本 2.x 的預設值是 true。The default for version 2.x in a consumption plan is true. 在專屬方案中,版本 2.x 的預設值是 false。The default for version 2.x in a dedicated plan is false.

輸出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 觸發程序會在 Functions 1.x 中傳回「HTTP 200 正常」與空白主體,或在 Functions 1 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.

輸出 - 設定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.

後續步驟Next steps

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