Azure Functions HTTP Trigger (.NET)

This document provides a comprehensive guide to using the HTTP trigger binding for Azure Functions written in .NET. The HTTP trigger allows your function to be invoked via an HTTP request, making it suitable for building web APIs, webhooks, and other request-driven services.

Key Concepts

The HTTP trigger binding allows you to:

Creating an HTTP Triggered Function

To create an HTTP-triggered function in .NET, you typically define a method decorated with the HttpTrigger attribute.

Example: Basic HTTP Trigger

Here's a simple example of a function that responds to GET requests:


using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace MyFunctionApp
{
    public static class HttpExample
    {
        [FunctionName("HttpExample")]
        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;

            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.";

            return new OkObjectResult(responseMessage);
        }
    }
}
            

Attribute Parameters

The HttpTrigger attribute has several important parameters:

Request and Response Handling

Accessing Request Data

The HttpRequest object provides access to various parts of the incoming request:

Returning Responses

The function should return an IActionResult. Common return types include:

Tip: For complex responses or custom headers, you can construct an HttpResponseMessage directly.

Advanced Scenarios

Custom Routes

You can define specific routes for your HTTP-triggered functions to create more structured APIs.


[FunctionName("GetUser")]
public static async Task<IActionResult> GetUser(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = "users/{userId}")] HttpRequest req,
    ILogger log,
    string userId)
{
    log.LogInformation($"Fetching user with ID: {userId}");
    // ... logic to fetch user
    return new OkObjectResult($"User data for ID: {userId}");
}
            

Request Body Deserialization

You can use libraries like Newtonsoft.Json or System.Text.Json to deserialize the request body into .NET objects.

Custom HTTP Methods

You can specify multiple HTTP methods for a single trigger:


[HttpTrigger(AuthorizationLevel.Function, "get", "put", Route = "items/{itemId}")]
            

Binding Configuration

The function.json file (or equivalent configuration in host.json and local.settings.json for .NET Core) defines the bindings. For an HTTP trigger, it typically looks like this:

Property Description
type httpTrigger
direction in
authLevel function (or anonymous, admin)
methods ["get", "post"]
route "api/{functionName}" (optional)
webjobs.script.functions..httptrigger This is implied by the attribute in .NET.

Best Practices

By mastering the HTTP trigger, you can unlock the full potential of Azure Functions for building scalable and responsive web applications.