Azure Functions HTTP Trigger Binding (.NET)

This article describes how to use the HTTP trigger binding with .NET in Azure Functions. The HTTP trigger allows your function to be invoked by an HTTP request. You can also use the HTTP trigger to return an HTTP response.

The HTTP trigger binding is commonly used to build serverless APIs and webhooks.

Key Concepts

  • Request Handling: Functions can process incoming HTTP requests.
  • Response Generation: Functions can return custom HTTP responses.
  • Routing: Define specific URL paths for your functions.
  • Methods: Specify allowed HTTP methods (GET, POST, PUT, DELETE, etc.).
  • Authorization: Control access to your HTTP-triggered functions.

Binding Configuration

The HTTP trigger is configured in the function.json file or using attributes in your .NET code.

Using Attributes (Recommended for .NET)

In .NET, you typically use attributes to define your HTTP trigger and bindings. The HttpTrigger attribute is used to define the trigger.


using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using System.Net;

public static class HttpExample
{
    [Function("HttpExample")]
    public static async Task<HttpResponseData> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
        FunctionContext context)
    {
        var logger = context.GetLogger("HttpExample");
        logger.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = System.Text.Json.JsonSerializer.Deserialize(requestBody);
        name = name ?? data?.name;

        string responseMessage = string.IsNullOrEmpty(name)
            ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            : $"Hello, {name}. This HTTP triggered function executed successfully.";

        var response = req.CreateResponse(HttpStatusCode.OK);
        response.WriteString(responseMessage);

        return response;
    }
}
                

Attribute Parameters

  • AuthorizationLevel: Specifies the level of authorization required (e.g., Anonymous, Function, Admin).
  • Methods: An array of strings specifying the HTTP methods allowed for this trigger (e.g., "get", "post").
  • Route: (Optional) Specifies a custom route for the function.

Using function.json

For non-.NET languages or specific scenarios, you can configure the HTTP trigger in function.json:


{
  "scriptFile": "__init__.py", // or similar for other languages
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
                

Request and Response Objects

The HTTP trigger provides access to the incoming HTTP request and allows you to create an HTTP response.

HttpRequestData

  • Url: The URL of the request.
  • Method: The HTTP method of the request.
  • Headers: A dictionary of request headers.
  • Query: A dictionary of query parameters.
  • Body: A stream representing the request body.
  • CreateResponse(): Method to create an HttpResponseData object.

HttpResponseData

  • StatusCode: The HTTP status code of the response.
  • Headers: A dictionary of response headers.
  • WriteString(string): Writes a string to the response body.
  • WriteBytes(byte[]): Writes a byte array to the response body.

Common Scenarios

  • REST APIs: Create endpoints for CRUD operations.
  • Webhooks: Receive notifications from other services.
  • Form Processing: Handle data submitted via HTML forms.
  • Proxies: Act as a proxy to other backend services.

Next Steps

Explore more advanced scenarios: