上传至AWS的极简Lambda函数抛出空引用异常问题排查
问题背景
本地环境:
- dotnet版本:6.0.400
- dotnet lambda工具版本:5.4.5
通过dotnet new serverless.AspNetCoreMinimalAPI -n TestCalc创建测试项目,本地VSCode按F5可正常运行,能返回localhost:5000/calculator响应。
部署步骤:
- AWS控制台创建新Lambda函数
- 函数URL认证类型设为NONE
- 勾选配置CORS
- 设置handler为TestCalc
- 将TestCalc.csproj中
PublishReadyToRun设为false - 本地执行
dotnet publish -c Release --output=publish发布项目 - 压缩publish文件夹内容为publish.zip
- 上传publish.zip到Lambda
调用函数URL时,CloudWatch出现空引用异常:
System.NullReferenceException: Object reference not set to an instance of an object.
at Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction.MarshallRequest(InvokeFeatures features, APIGatewayProxyRequest apiGatewayRequest, ILambdaContext lambdaContext)
at Amazon.Lambda.AspNetCoreServer.AbstractAspNetCoreFunction2.FunctionHandlerAsync(TREQUEST request, ILambdaContext lambdaContext) at Amazon.Lambda.RuntimeSupport.HandlerWrapper.<>c__DisplayClass26_02.<<GetHandlerWrapper>b__0>d.MoveNext()
--- End of stack trace from previous location ---
at Amazon.Lambda.RuntimeSupport.LambdaBootstrap.InvokeOnceAsync(CancellationToken cancellationToken)
项目代码(含自定义日志):
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Add AWS Lambda support. When application is run in Lambda Kestrel is swapped out as the web server with Amazon.Lambda.AspNetCoreServer. This // package will act as the webserver translating request and responses between the Lambda event source and ASP.NET Core. builder.Services.AddAWSLambdaHosting(LambdaEventSource.RestApi); var app = builder.Build(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.MapGet("/", () => "Welcome to running ASP.NET Core Minimal API on AWS Lambda"); app.Logger.LogInformation($"before app.Run()"); // appears in CloudWatch app.Run(); app.Logger.LogInformation($"after app.Run()"); // does NOT appear in CloudWatch
解决方法
1. 修正Lambda事件源配置
核心问题是代码里指定的事件源不对:你用的是Lambda Function URL,但代码里写的是LambdaEventSource.RestApi——RestApi对应API Gateway的事件结构,和Function URL的事件格式不兼容。
把代码里的事件源改成HttpApi:
// 替换原来的RestApi为HttpApi builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi);
2. 修正Handler设置
Lambda控制台的Handler不能只填TestCalc,得用完整的入口类路径:TestCalc::TestCalc.LambdaEntryPoint::FunctionHandlerAsync。默认模板会生成LambdaEntryPoint作为Lambda的入口类,必须指定到这个类的方法。
3. 规范发布和打包流程
- 发布时指定Linux运行时(Lambda默认用Linux环境):
dotnet publish -c Release -r linux-x64 --self-contained false --output publish - 打包时要把publish文件夹内部的所有文件压缩,不能把publish文件夹本身打包进去。确保zip根目录直接有
TestCalc.dll、Amazon.Lambda.AspNetCoreServer.dll这些文件,不是嵌套在publish文件夹里。
4. 升级Lambda工具包版本
你用的dotnet lambda工具版本5.4.5比较旧,可能和.NET 6存在兼容性问题,执行命令升级:
dotnet tool update -g Amazon.Lambda.Tools
验证修改
重新发布、打包、上传后,调用Function URL应该能正常返回响应,CloudWatch也不会再出现空引用异常。
内容的提问来源于stack exchange,提问作者Matt W

