.NET 7 Azure Durable Function:Http Trigger传参至Orchestration方法
在.NET 7 Azure Durable Function中传递Http请求负载给Orchestrator的标准实现
要将HttpTrigger接收的POST请求负载传递给Durable Orchestrator,标准流程分为以下三步:
1. 定义请求负载模型
首先创建可序列化的请求模型类,确保能在函数间正确完成序列化与反序列化:
public class CandidateProfileRequest { public string FullName { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } // 根据实际业务需求添加其他字段 }
2. 修改HttpTrigger函数读取请求体并启动Orchestrator
在HttpStart函数中读取POST请求内容,反序列化为模型对象,然后调用DurableTaskClient.StartNewAsync时将该对象作为Orchestrator的输入参数传入:
[Function("CreateCandidateProfileOrchestration_HttpStart")] public static async Task<HttpResponseData> HttpStart( [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req, [DurableClient] DurableTaskClient client, FunctionContext executionContext) { var logger = executionContext.GetLogger("CreateCandidateProfileOrchestration_HttpStart"); // 读取并反序列化请求体 var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var candidateRequest = JsonSerializer.Deserialize<CandidateProfileRequest>(requestBody); if (candidateRequest == null) { var badResponse = req.CreateResponse(HttpStatusCode.BadRequest); await badResponse.WriteStringAsync("无效的请求体"); return badResponse; } // 启动Orchestrator并传入请求参数 var instanceId = await client.StartNewAsync(nameof(CreateCandidateProfileOrchestration), candidateRequest); logger.LogInformation("已启动编排实例,ID = '{instanceId}'.", instanceId); var response = req.CreateResponse(HttpStatusCode.Accepted); response.Headers.Add("Location", client.CreateCheckStatusResponse(req, instanceId).Headers.Location); return response; }
3. 修改Orchestrator函数获取输入参数
在Orchestrator中使用TaskOrchestrationContext.GetInput<T>()方法获取传入的请求负载:
[Function(nameof(CreateCandidateProfileOrchestration))] public static async Task<List<string>> RunOrchestrator( [OrchestrationTrigger] TaskOrchestrationContext context) { var logger = context.CreateReplaySafeLogger(nameof(CreateCandidateProfileOrchestration)); logger.LogInformation("执行CreateCandidateProfileOrchestration编排"); // 获取传入的请求参数 var candidateRequest = context.GetInput<CandidateProfileRequest>(); if (candidateRequest == null) { throw new ArgumentNullException(nameof(candidateRequest), "编排输入参数不能为null"); } // 后续业务逻辑示例:调用Activity函数处理候选人生成逻辑 var result = new List<string>(); var profileId = await context.CallActivityAsync<string>(nameof(CreateCandidateProfileActivity), candidateRequest); result.Add(profileId); return result; }
可选:配套Activity函数示例
如果需要调用Activity处理具体业务逻辑,示例代码如下:
[Function(nameof(CreateCandidateProfileActivity))] public static string CreateCandidateProfileActivity( [ActivityTrigger] CandidateProfileRequest request, FunctionContext executionContext) { var logger = executionContext.GetLogger(nameof(CreateCandidateProfileActivity)); logger.LogInformation("为{FullName}创建候选人档案", request.FullName); // 模拟生成候选人ID return Guid.NewGuid().ToString(); }
内容的提问来源于stack exchange,提问作者R.A 1
相关产品推荐
相关产品推荐

