.NET Core 6+AWS Lambda无法处理请求体中的Base64数据
问题描述
使用VS 2022的「发布到Lambda」工具将.NET Core极简API部署至AWS Lambda,API功能为接收图片Base64字符串并上传至S3。调用接口时,若传入photo参数(非空Base64字符串),Lambda返回**(504)网关超时**;但photo为空时,端点可正常响应。
相关配置
1. Program.cs 托管代码
builder.Services.AddAWSLambdaHosting(LambdaEventSource.RestApi);
2. Postman 请求体
{ "photo": "/9j/4AAQSkZ.....", "ext": "png" }
3. server.template 配置
{ "AWSTemplateFormatVersion": "2010-09-09", "Transform": "AWS::Serverless-2016-10-31", "Description": "An AWS Serverless Application that uses the ASP.NET Core framework running in Amazon Lambda.", "Parameters": {}, "Conditions": {}, "Resources": { "AspNetCoreFunction": { "Type": "AWS::Serverless::Function", "Properties": { "Handler": "xxx", "Runtime": "dotnet6", "CodeUri": "", "MemorySize": 256, "Timeout": 30, "Role": null, "Policies": [ "AWSLambda_FullAccess", "AWSLambdaVPCAccessExecutionRole" ], "Events": { "ProxyResource": { "Type": "Api", "Properties": { "Path": "/{proxy+}", "Method": "ANY" } }, "RootResource": { "Type": "Api", "Properties": { "Path": "/", "Method": "ANY" } } } } } }, "Outputs": { "ApiURL": { "Description": "API endpoint URL for Prod environment", "Value": { "Fn::Sub": "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/" } } } }
4. aws-lambda-tools-defaults.json 配置
{ "Information" : [ "...." ], "profile" : "default", "region" : "ap-southeast-1", "configuration" : "Release", "s3-prefix" : "xxx/", "template" : "serverless.template", "template-parameters" : "", "s3-bucket" : "xxx", "stack-name" : "xxx" }
排查与解决方法
- 调整超时配置:API Gateway默认同步超时为29秒,当前Lambda
Timeout设为30秒,会导致网关先触发超时。将Lambda的Timeout改为28秒以内;若需处理大文件,启用API Gateway异步调用模式。 - 提升Lambda资源配置:Base64解码和S3上传对内存、CPU需求较高,当前256MB内存可能导致性能瓶颈。将
MemorySize提升至512MB或更高,Lambda的CPU性能随内存线性增长,能有效缩短执行时间。 - 检查VPC网络连通性:模板包含
AWSLambdaVPCAccessExecutionRole权限,若Lambda关联了VPC但未配置S3网关端点或NAT网关,会无法访问S3导致请求挂起。若不需要VPC,移除该权限并取消VPC配置;若必须用VPC,添加对应网络组件确保S3访问正常。 - 查看CloudWatch日志定位异常:登录AWS控制台进入CloudWatch日志组,查看Lambda执行日志,确认是Base64解码失败、S3上传超时还是其他错误导致执行停滞,针对性修复代码逻辑。
内容的提问来源于stack exchange,提问作者M. Ko
相关产品推荐
相关产品推荐

