AWS Lambda调用无法触发FunctionHandler的原因排查
场景与配置
首次将C# .NET Core应用部署至AWS Lambda,serverless模板中指定的Function Handler配置如下:
"Handler":"TestApplication::TestApplication.LambdaEntryPoint:MyFunctionHandler"
LambdaEntryPoint.cs类代码:
namespace TestApplication { public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction { protected override void Init(IWebHostBuilder builder) { Console.WriteLine("LambdaEntryPoint called."); builder.UseStartup<Startup>(); } public string MyFunctionHandler(object evnt, ILambdaContext context) { //Processing the event //This line is never reached Console.WriteLine("MyFunctionHandler called."); } } }
现象
使用AWS Mock Lambda Test Tool调试时,Init方法的日志能正常输出,但自定义的MyFunctionHandler方法从未被触发,断点也无法命中。此前找到过类似问题,但无法理解答案逻辑。
问题原因与解决方案
核心原因
你的LambdaEntryPoint继承了APIGatewayProxyFunction,这个类是AWS为ASP.NET Core Web API部署到Lambda专门设计的基类——它已经内置了Lambda的Handler入口方法(FunctionHandlerAsync),用于处理API Gateway的请求并映射到ASP.NET Core的请求管道。此时Lambda会直接调用基类的默认Handler方法,完全不会识别你自定义的MyFunctionHandler。
对应解决方案
分两种情况处理:
如果是部署ASP.NET Core Web API:
不需要自定义MyFunctionHandler,直接将Handler配置修改为基类的默认入口:"Handler":"TestApplication::TestApplication.LambdaEntryPoint::FunctionHandlerAsync"保持
Init方法的配置即可,API Gateway的请求会自动通过基类的Handler进入ASP.NET Core管道,由你的Startup类处理路由和业务逻辑。如果是编写普通Lambda函数(非Web API):
不要继承APIGatewayProxyFunction,改为创建普通类并实现Handler方法:namespace TestApplication { public class LambdaHandler { public string MyFunctionHandler(object evnt, ILambdaContext context) { Console.WriteLine("MyFunctionHandler called."); return "处理完成"; } } }同时修改Handler配置:
"Handler":"TestApplication::TestApplication.LambdaHandler:MyFunctionHandler"
内容的提问来源于stack exchange,提问作者Edward Elric

