EngineeringSolution ArchitectAzure Playbooks

Azure Functions – Playbook Kích Hoạt HTTP

Kịch bản

Cung cấp một Azure Function .NET 8 dưới dạng endpoint HTTP công khai, xác thực người gọi qua Azure AD B2C và điều phối một workflow Durable Functions.

Yêu cầu trước

  • Đăng ký Azure Subscription và tạo Function App (v4, .NET 8).
  • Tạo Azure AD B2C tenant và App Registration cho Function.
  • Managed Identity được bật trên Function App (khuyến nghị).

Các bước thực hiện

  1. Khởi tạo dự án Function
    bash
    func init MyHttpFunction --worker-runtime dotnet-isolated
    cd MyHttpFunction
    func new --name HttpTriggerOrder --template "Http Trigger" --authlevel "function"
    
  2. Thêm gói Durable Functions
    bash
    dotnet add package Microsoft.Azure.Functions.Worker.Extensions.DurableTask
    dotnet add package Microsoft.Azure.Functions.Worker.Sdk
    
  3. Triển khai HTTP Trigger
    csharp
    public class HttpTriggerOrder
    {
        private readonly IDurableClient _client;
        private readonly ILogger<HttpTriggerOrder> _log;
    
        public HttpTriggerOrder(IDurableClient client, ILogger<HttpTriggerOrder> log)
        {
            _client = client; _log = log;
        }
    
        [Function("HttpTriggerOrder")]
        public async Task<HttpResponseData> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "orders")] HttpRequestData req)
        {
            var payload = await req.ReadFromJsonAsync<OrderDto>();
            // Xác thực JWT từ Azure AD B2C (được middleware Function xử lý)
            string instanceId = await _client.StartNewAsync("OrderOrchestrator", payload);
            var response = req.CreateResponse(HttpStatusCode.Accepted);
            response.Headers.Add("Location", $"/api/orchestrations/{instanceId}");
            return response;
        }
    }
    
  4. Durable Orchestrator – có thể tái sử dụng từ ví dụ Service Bus hoặc tạo mới.
  5. Cấu hình Xác thực
    • Truy cập Azure Portal > Function App > Authentication / Authorization, bật Azure AD B2C.
    • Đặt Unauthenticated requests thành Redirect.
  6. Triển khai
    bash
    func azure functionapp publish my-http-func-app
    
  7. Kiểm thử
    bash
    curl -X POST https://my-http-func-app.azurewebsites.net/api/orders \
         -H "Authorization: Bearer <b2c_token>" \
         -H "Content-Type: application/json" \
         -d '{"CustomerId": "123", "Items": [{"Sku":"ABC","Qty":2}]}'
    
    Kỳ vọng trả về 202 Accepted và header Location chỉ tới trạng thái orchestrator.

Mẹo thực hành tốt

  • Idempotency: Thêm CorrelationId do client sinh ra trong payload, lưu trong trạng thái orchestrator để bỏ qua các yêu cầu trùng lặp.
  • Timeout: Bật DurableTaskOptions.ExtendedSessionsEnabled = true để hỗ trợ workflow dài hạn.
  • Quan sát: Kích hoạt Application Insights; Durable Functions tự phát OrchestrationStarted, OrchestrationCompleted.

File thuộc mục Azure Playbooks của senior‑dotnet‑wiki.