使用 asp.net core 的无服务器模板的 aws lambda 函数

问题描述

我对 aws 没有足够的了解,但我的公司要求我做一份工作,我猜这就是 AWS Lambda 的完美表现。要求是我必须创建一个服务,该服务的端点需要每天调用两次。我遵循的方法是我通过 Visual Studio 创建了一个无服务器 Web API,并为每个端点创建了 API 网关端点。然后通过云监视事件添加一个触发器,每天运行两次,但每当触发该功能时,我都会收到此错误

Object reference not set to an instance of an object.: NullReferenceException
   at Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction.MarshallRequest(InvokeFeatures features,APIGatewayProxyRequest apiGatewayRequest,ILambdaContext lambdaContext)
   at Amazon.Lambda.AspNetCoreServer.AbstractAspNetCoreFunction`2.FunctionHandlerAsync(TREQUEST request,ILambdaContext lambdaContext)
   at lambda_method(Closure,Stream,LambdaContextInternal )

解决方法

我有同样的问题,最近可以解决。

如果您将 Lambda 与 ASP.NET Core 一起使用,您应该拥有 LambdaEntryPoint 类来处理所有请求。 尝试覆盖此类中的 MarshallRequest 方法,添加日志记录并查看 apiGatewayRequest 参数中的内容。代码可能如下所示:

protected override void MarshallRequest(InvokeFeatures features,APIGatewayProxyRequest apiGatewayRequest,ILambdaContext lambdaContext)
{
    LambdaLogger.Log($"Request path: {apiGatewayRequest.Path}");
    LambdaLogger.Log($"Request path parameters: {apiGatewayRequest.PathParameters}");
    LambdaLogger.Log($"Request body: {apiGatewayRequest.Body}");
    LambdaLogger.Log($"Request request context: {apiGatewayRequest.RequestContext}");
    base.MarshallRequest(features,apiGatewayRequest,lambdaContext);
}

就我而言,所有这些值都是空值。其原因是使用 Amazon EventBridge 保持 Lambda 在线以避免冷启动。如果您还使用 EventBridge,请尝试在那里正确配置请求。如果没有,您可以尝试通过以下方式更新 MarshalRequest

protected override void MarshallRequest(InvokeFeatures features,ILambdaContext lambdaContext)
{
    if(apiGatewayRequest.RequestContext == null) //Or other property
    {
        return;
    }

    base.MarshallRequest(features,lambdaContext);
}