Twilio .NET 7中Gather组件SpeechResult始终为null的问题求助
解决Twilio .NET 7中Gather组件SpeechResult参数为null的问题
核心修复步骤
1. 显式指定表单参数绑定源
Twilio触发Gather的action时,会以application/x-www-form-urlencoded格式提交数据,而非JSON。ASP.NET Core默认不会自动将表单字段绑定到POST方法参数,需添加[FromForm]特性明确绑定源:
[HttpPost] public TwiMLResult HandleGather([FromForm] string SpeechResult, [FromForm] double? Confidence, [FromForm] string SpeechError) { if (!string.IsNullOrEmpty(SpeechError)) { Console.WriteLine($"Error: {SpeechError}"); } else if (!string.IsNullOrEmpty(SpeechResult)) { if (Confidence.HasValue && Confidence >= 0.8) { Console.WriteLine($"You said: {SpeechResult}. Thank you!"); } else { Console.WriteLine($"I think you said: {SpeechResult}, but I'm not sure. Please try again."); } } else { Console.WriteLine("Sorry, I didn't catch that."); } // 必须返回TwiML响应,否则Twilio会判定请求失败 var response = new VoiceResponse(); response.Append(new Say("Processing complete.", Say.VoiceEnum.PollyJoannaNeural)); return TwiML(response); }
注意:将Confidence设为可空类型double?,避免识别失败时因字段缺失导致绑定错误。
2. 验证Action路由的正确性
检查Url.Action生成的路由是否匹配HandleGather端点,可临时打印URL确认:
var redirectUrl = Url.Action(nameof(IncomingCallController.HandleGather), nameof(IncomingCallController).RemoveController()); Console.WriteLine($"Gather Action URL: {redirectUrl}");
本地开发时需确保Twilio能通过ngrok等工具访问到你的服务,且路由未被中间件拦截。
3. 调试表单数据(排查用)
若问题仍存在,可直接读取原始表单数据验证字段是否存在:
[HttpPost] public TwiMLResult HandleGather() { var speechResult = Request.Form["SpeechResult"]; var confidence = Request.Form["Confidence"]; var speechError = Request.Form["SpeechError"]; Console.WriteLine($"SpeechResult: {speechResult}, Confidence: {confidence}, SpeechError: {speechError}"); // 原有逻辑及返回语句... }
内容的提问来源于stack exchange,提问作者William
相关产品推荐
相关产品推荐

