AWS Lambda C# - Accessing custom context

Viewed 5872

I have a simple Lambda function written in .NET Core (C#) that uses the APIGatewayProxyRequest object to go through all the request properties.

If I test this lambda function (from AWS Lambda), and pass it a sample event config that contains basic information:

enter image description here

I can get this information like so:

public string FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        logger.Logger.Log($"Body: {request.Body}  \n");
        logger.Logger.Log($"Path: {request.Path}  \n");
        logger.Logger.Log($"Resource: {request.Resource}  \n");

How is it that I can access custom context or authorizer values from the same data:

enter image description here

I have tried:

logger.Logger.Log($"RequestContext Authorizor: {request.RequestContext.Authorizer}  \n");

Including it's different properties (StringKey, PrincipleId etc.)

It seems from Node.js, this would be simply achieved by using this:

event.requestContext.authorizer.customKey

There is no such thing in C#?

2 Answers

I don't know if people are wondering about this even today (after almost 3 years - I was), I have figured out a way. Could be helpful.

Note: This is only for a lambda built using the DotNet SDK.

In the AWS API G/W mapping template, you need to create a JSON template which matches the ApiGatewayProxyRequest class so that it can be deserialized. In the example below, I am trying to extract the body from the request and the source ip and user agent from the context of the request.

{
    "Body": "$util.escapeJavaScript($input.body)",
    "RequestContext" : {
    "Identity" : {
        "SourceIp" : "$context.identity.sourceIp",
        "UserAgent" :  "$context.identity.userAgent"
    },
    "RequestId" : "$context.requestId"
}

}

Now, for accessing these values in your lambda, you can do the following:

public async Task<SomeResponse> FunctionHandler(APIGatewayProxyRequest gatewayProxyRequest, ILambdaContext context)
    {
        var requestContext = gatewayProxyRequest.RequestContext;
        var sourceIP = requestContext?.Identity?.SourceIp;
        var body = gatewayProxyRequest.Body;
        .
        .
        .
    }
Related