aws-lambda-dotnet: Null Reference Exception coming from APIGatewayProxyFunction

I’ve beaten this one to death as best I can before posting here because I’ve got to be missing something, but at this point I just can’t figure it out.

I’ve published to AWS Lambda from Visual Studio 2017 using the serverless template and S3 stack as well as just publishing straight there. I’ve also tried just uploading a zip file. Every time I test from the API Gateway or the tools in Visual Studio, I get the following exception.

{
	  "errorType": "AggregateException",
	  "errorMessage": "One or more errors occurred. (Object reference not set to an instance of an object.)",
	  "stackTrace": [
		"at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)",
		"at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)",
		"at lambda_method(Closure , Stream , Stream , ContextInfo )"
	  ],
	  "cause": {
		"errorType": "NullReferenceException",
		"errorMessage": "Object reference not set to an instance of an object.",
		"stackTrace": [
		  "at Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction.MarshallRequest(InvokeFeatures features, APIGatewayProxyRequest apiGatewayRequest)",
		  "at Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction.<FunctionHandlerAsync>d__12.MoveNext()"
		]
	  }
	}

I used the following blog to make sure I deployed correctly: https://aws.amazon.com/blogs/developer/deploy-an-existing-asp-net-core-web-api-to-aws-lambda/

Lambda Entry Point:

public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
    {
        protected override void Init(IWebHostBuilder builder)
        {
            try
            {
                builder
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseStartup<Startup>()
                    .UseApiGateway();
            }
            catch (Exception ex)
            {
                LambdaLogger.Log("Exception throw in LambdaEntryPoint: " + ex);
            }
        }
    }

.csproj contents

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.0</TargetFramework>
    <PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
    <PreserveCompilationContext>false</PreserveCompilationContext>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Amazon.Lambda.AspNetCoreServer" Version="0.10.2-preview1" />
    <PackageReference Include="Amazon.Lambda.Core" Version="1.0.0" />
    <PackageReference Include="Amazon.Lambda.Logging.AspNetCore" Version="1.0.0" />
    <PackageReference Include="Amazon.Lambda.Tools" Version="1.8.0" />
    <PackageReference Include="AWSSDK.Core" Version="3.3.17.10" />
    <PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="3.3.3" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.0.5" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.4" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.0.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.0.5" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="1.0.5" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational.Design" Version="1.0.5" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.0.5" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.0.5" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.0.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.0.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.0.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.0.0" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.2" />
    <DotNetCliToolReference Include="Amazon.Lambda.Tools" Version="1.8.0" />
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="Controllers\" />
    <Folder Include="Data\" />
    <Folder Include="Models\" />
    <Folder Include="Views\Shared\" />
    <Folder Include="wwwroot\css\" />
    <Folder Include="wwwroot\js\" />
  </ItemGroup>

</Project>

I tried getting the serverless invoke local command to work, but it wouldn’t for whatever reason. So, I’m at a loss on how to debug this and get to what’s throwing the null reference exception out of the SDK.

Thanks, and please let me know if you need anything else from me.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 1
  • Comments: 31 (5 by maintainers)

Most upvoted comments

Closing for lack of activity and it sounds like the issue was resolved. As this issue has gotten long and hard to follow. If there are still issues please open a new issue.

getting this error after changing the default serverless web API project to use APIGatewayHttpApiV2ProxyFunction and JsonConvert.DeserializeObject<APIGatewayHttpApiV2ProxyRequest>(requestStr)

Steps to reproduce:

  • 1 Create new project from template.
  • 2 Change to use APIGatewayHttpApiV2ProxyFunction in LambdaEntryPoint
  • 3 Change to use APIGatewayHttpApiV2ProxyRequest in ValuesControllerTests
  • 4 Run test

Make sure your API Gateway integration have the correct payload format version set (API Gateway -> Integrations -> Manage integrations -> Payload format version)

In my case I had to change base class from APIGatewayProxyFunction to APIGatewayHttpApiV2ProxyFunction. Leaves this here in case anybody else have the same issue 😃

Edit: My suggestion only works for HTTP api gateway. If your’re using REST api gateway, you should use APIGatewayProxyFunction instead as @harry-hathorn pointed out

@torbjokv In my case i had to change from APIGatewayHttpApiV2ProxyFunction to APIGatewayProxyFunction

It seems like APIGatewayProxyFunction works for using a REST api gateway and APIGatewayHttpApiV2ProxyFunction works for HTTP api gateway.

For anyone Googling, I had this issue, but as pointed out, it is intended to be used for lamda proxy integrations. The following solved it for me.

  • When you go to Actions -> Create Resource, I found Configure as proxy resource must be checked,
  • Afterwards, “Use Lambda Proxy Integration” must also be checked in the “Integration Request” page of the API Gateway config.

Screenshot from 2019-09-26 12-07-08

Quick comment if you are here maybe searching for why you’re API Gateway cannot contact the lambda or you get a 404 code when calling the lambda. If like me you are using the barebone lambda example, dont forget that there is a “api” part in the path of the web API. For example in the ValueController, you should call api/values not just values. Very stupid but took me an hour to find sadly.

I can confirm that the issue is related to the request payload sent by the Lambda test. For anyone finding this, here’s the working payload for the default Values controller:

{
  "body": "{\"test\":\"body\"}",
  "resource": "/{proxy+}",
  "requestContext": {
    "resourceId": "123456",
    "apiId": "1234567890",
    "resourcePath": "/{proxy+}",
    "httpMethod": "GET",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
    "accountId": "123456789012",
    "identity": {
      "apiKey": null,
      "userArn": null,
      "cognitoAuthenticationType": null,
      "caller": null,
      "userAgent": "Custom User Agent String",
      "user": null,
      "cognitoIdentityPoolId": null,
      "cognitoIdentityId": null,
      "cognitoAuthenticationProvider": null,
      "sourceIp": "127.0.0.1",
      "accountId": null
    },
    "stage": "prod"
  },
  "queryStringParameters": {
    "foo": "bar"
  },
  "headers": {
    "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
    "Accept-Language": "en-US,en;q=0.8",
    "CloudFront-Is-Desktop-Viewer": "true",
    "CloudFront-Is-SmartTV-Viewer": "false",
    "CloudFront-Is-Mobile-Viewer": "false",
    "X-Forwarded-For": "127.0.0.1, 127.0.0.2",
    "CloudFront-Viewer-Country": "US",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Upgrade-Insecure-Requests": "1",
    "X-Forwarded-Port": "443",
    "Host": "1234567890.execute-api.us-east-1.amazonaws.com",
    "X-Forwarded-Proto": "https",
    "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
    "CloudFront-Is-Tablet-Viewer": "false",
    "Cache-Control": "max-age=0",
    "User-Agent": "Custom User Agent String",
    "CloudFront-Forwarded-Proto": "https",
    "Accept-Encoding": "gzip, deflate, sdch"
  },
  "pathParameters": {
    "proxy": "api/values"
  },
  "httpMethod": "GET",
  "stageVariables": {
    "baz": "qux"
  },
  "path": "api/values"
}

I’m also receiving this error:

{
    "errorType": "AggregateException",
    "errorMessage": "One or more errors occurred. (Object reference not set to an instance of an object.)",
    "stackTrace": [
        "at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)",
        "at lambda_method(Closure , Stream , Stream , LambdaContextInternal )"
    ],
    "cause": {
        "errorType": "NullReferenceException",
        "errorMessage": "Object reference not set to an instance of an object.",
        "stackTrace": [
            "at Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction.MarshallRequest(InvokeFeatures features, APIGatewayProxyRequest apiGatewayRequest, ILambdaContext lambdaContext)",
            "at Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction.<FunctionHandlerAsync>d__13.MoveNext()"
        ]
    }
}

I have tried enabling “Use Lambda Proxy integration”, but there has been zero change with this option enabled.

I compiled using .NET Core 2. Microsoft.AspNetCore.All is set to 2.0.3.