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

k.j*_*abs 5 lambda triggers amazon-web-services asp.net-core-webapi aws-serverless

我对 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 , Stream , LambdaContextInternal )
Run Code Online (Sandbox Code Playgroud)

Gri*_*dko 4

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

如果将 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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

    base.MarshallRequest(features, apiGatewayRequest, lambdaContext);
}
Run Code Online (Sandbox Code Playgroud)