C# AWS Lambda API Gateway from browser - parameters not working

Viewed 276

With a simple C# AWS Lambda

        public string FunctionHandler(string myParam1, ILambdaContext context)
        {
            return myParam1;
        }

How should I pass parameters to an AWS Lambda function + API Gateway, via a browser GET request? I'd like something like this for example: https://[API ID].execute-api.[REGION].amazonaws.com/myFunc?myParam1=myValue1

In the browser it says {"message":"Internal Server Error"}

In the logs it says Error converting the Lambda event JSON payload to a string. JSON strings must be quoted, for example "Hello World" in order to be converted to a string: The JSON value could not be converted to System.String.

Without parameters it works, for example:

        public string FunctionHandler(ILambdaContext context)
        {
            return Utf8Json.JsonSerializer.ToJsonString(context);
        }

When sending a GET request in the browser https://[API ID].execute-api.[REGION].amazonaws.com/myFunc returns successfully {"AwsRequestId":"86ca2da9-438c-4865-8a0b-29d3ced37176","FunctionName":....

1 Answers

Ok I found a solution, instead of using the built-in parsing of parameters, it's possible to read a full JSON of parameters by reading a stream instead:

public string FunctionHandler(Stream requestStream, ILambdaContext context) { ... }

The requestStream here will have the parameters of GET/POST inside or a larger JSON, but have to be manually parsed. Note that the parameters may be sent b64 encoded (or probably also compressed). A good way would be to find a library which does this parsing. In my case, I also write the consumer JS code, so I can ensure the parameters will always come in the same fashion so my problem is solved but if someone has knows a good library for this, please tell.

Example of a manual POST request data extraction which also supports b64 encoding:

        public class StreamBody
        {
            public string body;
            public bool isBase64Encoded;
        }

        public string FunctionHandler(Stream requestStream, ILambdaContext context)
        {
            using var sr = new StreamReader(requestStream);
            var input = sr.ReadToEnd();
            var sbody = Utf8Json.JsonSerializer.Deserialize<StreamBody>(input);
            var body = !sbody.isBase64Encoded ? sbody.body : Encoding.UTF8.GetString(Convert.FromBase64String(sbody.body));
Related