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
- 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" - Thêm gói Durable Functions
bash
dotnet add package Microsoft.Azure.Functions.Worker.Extensions.DurableTask dotnet add package Microsoft.Azure.Functions.Worker.Sdk - 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; } } - Durable Orchestrator – có thể tái sử dụng từ ví dụ Service Bus hoặc tạo mới.
- 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.
- Triển khai
bash
func azure functionapp publish my-http-func-app - Kiểm thử
Kỳ vọng trả về 202 Accepted và headerbashcurl -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}]}'Locationchỉ tới trạng thái orchestrator.
Mẹo thực hành tốt
- Idempotency: Thêm
CorrelationIddo 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.