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:
- Define HTTP routes and methods for your functions.
- Access request details such as headers, query parameters, and the request body.
- Construct and return HTTP responses, including status codes, headers, and response bodies.
- Handle different content types for requests and responses.
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:
AuthorizationLevel: Specifies the authorization level required to access the function (e.g.,Anonymous,Function,Admin).methods: An array of HTTP methods that the trigger should respond to (e.g.,"get","post","put","delete").Route: Defines a custom route for the function. Ifnull(default), the route is derived from the function's name.
Request and Response Handling
Accessing Request Data
The HttpRequest object provides access to various parts of the incoming request:
req.Query: A dictionary of query parameters.req.Headers: A dictionary of request headers.req.Body: A stream for reading the request body.req.Method: The HTTP method of the request.req.Path: The path of the request.
Returning Responses
The function should return an IActionResult. Common return types include:
OkObjectResult: Returns a 200 OK status with a JSON or plain text body.BadRequestObjectResult: Returns a 400 Bad Request status.NotFoundResult: Returns a 404 Not Found status.CreatedAtRouteResult: Returns a 201 Created status with a location header.
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. |
This is implied by the attribute in .NET. |
Best Practices
- Use specific HTTP methods (GET, POST, PUT, DELETE) for clarity.
- Implement proper error handling and return appropriate HTTP status codes.
- Validate input data to prevent security vulnerabilities.
- Consider using a dedicated routing library or pattern for complex APIs.
- Leverage Dependency Injection for services and logging.
By mastering the HTTP trigger, you can unlock the full potential of Azure Functions for building scalable and responsive web applications.